(轉載)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 Result的content negotiation代替Web Api中預設的content negotiation。
Conneg通過實現IContentNegotiator的
下面的方法通過傳遞一個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的功能,而且沒有額外的開銷。