且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何强制 ASP.NET Web API 始终返回 JSON?

更新时间:2023-02-15 17:58:31

在 ASP.NET Web API 中仅支持 JSON – 正确的方法

用 JsonContentNegotiator 替换 IContentNegotiator:

Replace IContentNegotiator with JsonContentNegotiator:

var jsonFormatter = new JsonMediaTypeFormatter();
//optional: set serializer settings here
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

JsonContentNegotiator 实现:

JsonContentNegotiator implementation:

public class JsonContentNegotiator : IContentNegotiator
{
    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"));
    }
}