Asp.net web api 设置Api.Controller.Json函数以使用全局SerializerSettings

Asp.net web api 设置Api.Controller.Json函数以使用全局SerializerSettings,asp.net-web-api,json.net,Asp.net Web Api,Json.net,在ASP.NET Web API控制器中,我使用的JsonResults如下: return Json(data); 我在WebApiConfig中设置了全局默认值,正如我在许多地方所建议的那样 HttpConfiguration config = GlobalConfiguration.Configuration; config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopH

在ASP.NET Web API控制器中,我使用的JsonResults如下:

return Json(data);
我在WebApiConfig中设置了全局默认值,正如我在许多地方所建议的那样

HttpConfiguration config = GlobalConfiguration.Configuration;
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new StringEnumConverter());
我以为这会使设置被使用,但事实并非如此。为了解决这个问题,我打电话:

return Json(data, GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings);
这很好,但是我是否缺少一些东西使全局序列化设置始终适用?

通过调用Json(数据),您正在执行此重载-您可以看到它正在创建序列化程序设置的新实例

    protected internal JsonResult<T> Json<T>(T content)
    {
        return Json<T>(content, new JsonSerializerSettings());
    }
受保护的内部JsonResult Json(T内容)
{
返回Json(内容,新的JsonSerializerSettings());
}
如果使用返回协商结果的ApiController方法之一,例如
return Ok(data)
,则格式化程序将从全局配置中解析,您将看到所需的行为