问题描述
我在.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?
例如:
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>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)