【发布时间】:2018-04-12 05:35:21
【问题描述】:
我创建了一个 ASP.NET 2.0 webapi,并试图从返回 IActionResult 的方法中返回一个抽象类型,即
// GET api/trades/5
[HttpGet("{id}", Name = "GetTrade")]
[ProducesResponseType(typeof(Trade), 200)]
[ProducesResponseType(404)]
public IActionResult Get(int id)
{
var item = _context.Trades.FirstOrDefault(trade => trade.Id == id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
Trade 类型是一个抽象基类,我希望序列化的 JSON 包含 $type 属性,以便客户端可以反序列化为正确的具体类型。如果我将方法更改为返回 Trade(返回的 json 包含具有具体类型名称的 $type 属性)但不包含 IActionResult(无 $type 属性),则下面的代码控制输出序列化程序。
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services
.AddDbContext<RiskSystemDbContext>(opt => opt.UseInMemoryDatabase("RiskSystemDb"));
services
.AddMvc(options => {})
.AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
options.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;
});
}
如何为 IActionResult 设置 TypeNameHandling?
编辑:
对于一个类 FutureTrade : Trade {} 我期望
{
"$type": "RiskSystem.Model.FutureTrade, RiskSystem.Model",
"id": 1,
"createdDateTime": "2018-04-12T15:59:11.3680885+12:00"
...
}
得到
{
"id": 1,
"createdDateTime": "2018-04-12T15:59:11.3680885+12:00"
...
}
以下按预期工作
// GET api/trades
[HttpGet]
public IEnumerable<Trade> Get()
{
return _context.Trades.ToList();
}
问候 戴夫
【问题讨论】:
-
请包含一些预期的和实际的 json 对象结构,这些结构会返回给您的 JS 客户端。这将帮助每个人可视化您的问题。
-
我已按要求进行了编辑(尽管客户端是 .Net 而不是 JS)
-
你可以试试这个选项
options.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects -
谢谢,这似乎一直有效。添加为适当的解决方案,我会将其标记为答案。
-
@user2981639 默认 web api 使用 JSON.NET 序列化程序设置为
TypeNameHandling.None所以 $type 不包括在内,您可以根据需要更改它。
标签: c# asp.net-web-api .net-core