控制ASP.Net Core 2.0的SerializerSettings返回IActionResult

时间:2018-04-12 05:35:21

标签: c# asp.net-web-api .net-core

我创建了一个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();
    }

此致 戴夫

1 个答案:

答案 0 :(得分:1)

将TypeNameHandling从Auto更改为Objects将强制JSON序列化程序始终发出类型名称。

请从

更改TypeNameHandling
options.SerializerSettings.TypeNameHandling = TypeNameHandling.Auto;

options.SerializerSettings.TypeNameHandling = TypeNameHandling.Objects