我在.NETCore3.1WebAPI控制器上有一个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 header 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>