Web Api 中返回JSON的正確做法


在使用Web Api的時候,有時候只想返回JSON;實現這一功能有多種方法,本文提供兩種方式,一種傳統的,一種作者認為是正確的方法。

JSON in Web API – the formatter based approach

只支持JSON最普遍的做法是:首先清除其他所有的formatters,然后只保留JsonMediaTypeFormatter

有了HttpConfiguration的實例,你將會很簡單的清除所有formatters,然后重新添加JsonMediaTypeFormatter

實現代碼如下:

configuration.Formatters.Clear();
configuration.Formatters.Add(new JsonMediaTypeFormatter());

這種方式雖然可以實現功能,但是所有的conent negotiation還是會發生,這就會產生以下額外的開銷了。因為,你已經知道要返回的結果了,也只想返回Json,其他的content negotiation都不需要了。

下面的方法可以很好的解決這個問題。

 

JSON in Web API – the conneg based approach

最好的方法是使用自定義的只返回Json Resultcontent negotiation代替Web Api中默認的content negotiation

Conneg通過實現IContentNegotiatorNegotiator方法實現擴展。Negotiator方法返回ContentNegotiationResult(它包裝了你選擇的headersformatter)。

下面的方法通過傳遞一個JsonMediaTypeFormatter給自定義的conneg negotiator,讓它一直返回applicaton/json content-type以及JsonMediaTypeFormatter。這種方法避免了每次請求都要重新創建一次formatter

代碼如下:

public class JsonContentNegotiator : IContentNegotiator
{
    private readonly JsonMediaTypeFormatter _jsonFormatter;

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

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

接下來,你需要在HttpConfiguration實例上注冊你的新的實現機制:

 

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

 

通過替換默認的DefaultContentNegotiator,我們使用我們自定義的JsonContentNegotiator,它只支持Json,而且可以馬上返回。

如果你想更深入的了解Content Negotiation的知識,你可以查看作者的這篇文章

總結

通過使用自定義的JsonContentNegotiator替換系統默認的DefaultContentNegotiator,很好的實現Web Api只返回Json的功能,而且沒有額外的開銷。

 

 

原文地址:http://www.strathweb.com/2013/06/supporting-only-json-in-asp-net-web-api-the-right-way/

 

作者對Content Negotiation的講解:http://www.strathweb.com/2012/07/everything-you-want-to-know-about-asp-net-web-api-content-negotation/

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM