【发布时间】:2021-02-22 11:20:46
【问题描述】:
我有 API 模型请求的类层次结构:
public class Human
{
public string Name { get; set; }
public byte Age { get; set; }
public IEnumerable<HumanData> Data { get; set; }
}
public abstract class HumanData
{
public Guid Id { get; set; }
public string Text { get; set; }
public virtual string Type => GetType().Name;
}
public class HealthData : HumanData
{
public byte Weight { get; set; }
public byte Growth { get; set; }
public string Pressure { get; set; }
}
public class AddressData : HumanData
{
public string City { get; set; }
public string Street { get; set; }
public uint House { get; set; }
public uint Apartment { get; set; }
}
我创建了用于添加人类的 API:
[ApiController]
public class HumanController : ControllerBase
{
...
[HttpPost]
public async Task<IActionResult> Add([FromBody] Human humanRequest)
{
//Functionality
}
}
我调用 API 并传递请求模型:
{
"Name":"Alex",
"Age":30
"Data":[{
"Id": "10",
"Text":"Residence address",
"City":"Elblag",
"Street":"1 maja",
"House":"95",
"Type":"AddressData",
},{
"Id": "5",
"Text":"Residence address",
"Weight":"75",
"Growth":"179",
"Pressure":"120/85",
"Type":"HealthData",
}]}
但是请求模型没有被拉入humanRequest 变量。原因在于Data 字段HumanData 类层次结构。如何进行这样的绑定?
【问题讨论】:
-
您使用的是哪个 JSON 序列化程序?
-
我正在使用 NewtonsoftJson。
标签: c# .net asp.net-core asp.net-core-webapi asp.net-core-3.1