Swashbuckle自定义JsonSerializer设置

时间:2017-10-18 14:40:27

标签: json.net asp.net-web-api2 swagger swashbuckle

将SwashBuckle 5.6.0与WebAPI 5.2.3和NewtonSoft.Json 8.0.3一起使用我在尝试加载Swagger网页时遇到错误。 问题归结为SwaggerUI无法处理null对象的path部分中的spec方法。

一个简单的解决方法是添加

var jsonFormatter = new JsonMediaTypeFormatter
{
  SerializerSettings = new JsonSerializerSettings
  {
    NullValueHandling = NullValueHandling.Ignore
  }
};
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

到Global.asax,但这会破坏客户端的API。 现在有没有办法在不改变全局设置的情况下专门为Swagger更改JsonSerializerSettings

编辑:

GlobalConfiguration.Configuration.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(new JsonMediaTypeFormatter()));添加到Global.asax,这里是JsonContentNegotiator类。这将触发问题

public class JsonContentNegotiator : IContentNegotiator
{
    //http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/
    private readonly JsonMediaTypeFormatter _jsonFormatter;

    public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
    {
        _jsonFormatter = formatter;
    }

    public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
    {
        return new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
    }
}

编辑2: 通过删除JsonContentNegotiator类并添加:

来修复它
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());

0 个答案:

没有答案
相关问题