在默認情況下,當我們新建一個webapi項目,會自動返回XML格式的數據,如果我們想返回JSON的數據,可以設置下面的三種方法。
1. 不用改配置文件,在Controller的方法中,直接返回HttpResponseMessage
public HttpResponseMessage ReturnJson() { //初始化測試對象 TestJsonObj t = new TestJsonObj(); t.Name = "alun"; t.Address = "GZ"; //OBJ轉化成JSON string json = JsonConvert.SerializeObject(t); //返回json數 return new HttpResponseMessage() { Content = new StringContent(json, Encoding.UTF8, "application/json"), }; }
TestJsonObj是我們測試的類
上面的方法比較繁雜,但是靈活。每次都要把對象轉換成JSON,效率上有點慢。
2. 在全局設置中,把所有返回的格式清除,設置JSON。所有的返回的xml格式都會被清除
在WebApiConfig類的Register方法中,我們添加下面代碼:
config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter());
這種方式雖然可以實現功能,但是所有的conent negotiation還是會發生,這就會產生以下額外的開銷了。因為,你已經知道要返回的結果了,也只想返回Json,其他的content negotiation都不需要了。
3. 在全局設置中,使用自定義的只返回Json Result。只讓api接口中替換xml,返回json
在WebApiConfig類的Register方法中,我們添加下面代碼:
var jsonFormatter = new JsonMediaTypeFormatter(); config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
使用自定義的只返回Json Result的content negotiation代替Web Api中默認的content negotiation。
本文推薦方法3,因為簡單好用。
注意:
如果使用了swagger:
當使用方法1,在swagger頁面上,返回的obj的說明文檔不會顯示出來
當使用方法3,swagger說明文檔會一直處於fetching resource的狀態。
所以我們在測試的時候使用方法2,正式環境的時候使用方法3,做一個判斷就可以了,如下:
//設置返回json if (CPublicAttribute.TestEnviroment) { config.Formatters.Clear(); config.Formatters.Add(new JsonMediaTypeFormatter()); } else { var jsonFormatter = new JsonMediaTypeFormatter(); config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));