就像从具有expando对象的对象一样返回XML

我在.net Core 3.1 Web API控制器上有一个get方法,该方法返回从模型类生成的expando对象。

public class MyModel 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

[HttpGet("{id}")]
public async Task<IactionResult> Getasync(int id)
{
    var recordFromDB = await dbService.Getasync(id);

    if (recordFromDB == null)
        return NotFound();

    var returnmodel = mapper.Map<MyModel>(recordFromDB).ShapeData(null);

    return Ok(returnmodel);
}

public static ExpandoObject ShapeData<tsource>(this tsource source,string fields)
{
    var dataShapedObject = new ExpandoObject();

    if (string.IsnullOrWhiteSpace(fields))
    {
        var propertyInfos = typeof(tsource).GetProperties(Bindingflags.Public | Bindingflags.Instance);

        foreach (var propertyInfo in propertyInfos)
        {
            var propertyValue = propertyInfo.Getvalue(source);

            ((IDictionary<string,object>)dataShapedObject).Add(propertyInfo.Name,propertyValue);
        }

        return dataShapedObject;
    }

    ... more of the method here but it's never hit so I've removed the code
}

如果我使用accept标头application / json对该记录进行get请求,则一切正常,并且json的格式符合预期。

但是,如果我将accept头更改为application / xml,它可以工作,但是被格式化为键值对(我得到的expando对象是键值对字典)

<ArrayOfKeyValueOfstringanyType xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <KeyValueOfstringanyType>
        <Key>Id</Key>
        <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:int">1</Value>
    </KeyValueOfstringanyType>
    <KeyValueOfstringanyType>
        <Key>Name</Key>
        <Value xmlns:d3p1="http://www.w3.org/2001/XMLSchema" i:type="d3p1:string">string</Value>
    </KeyValueOfstringanyType>
</ArrayOfKeyValueOfstringanyType>

此xml是否可以以某种方式被掩盖,使其看起来像普通对象中的xml?

例如:

如果我删除ShapeData方法调用,那么:

var a = mapper.Map<MyModel>(recordFromDB);

我收到以下xml:

<MyModel xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/MyProject.Models">
    <Name>string</Name>
    <Id>1</Id>
</MyModel>
iCMS 回答:就像从具有expando对象的对象一样返回XML

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/1688198.html

大家都在问