C# web api傳回類型設定為json的兩種方法
web api寫api介面時預設回傳的是把你的物件序列化後以XML形式返回,那麼怎樣才能讓其返回為json呢,下面就介紹兩種方法:
方法一:(改配置法)
找到Global.asax文件,在Application_Start()方法中加入一句:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
修改後:
<br>protected void Application_Start() <br>{ <br>AreaRegistration.RegisterAllAreas(); <br>WebApiConfig.Register(GlobalConfiguration.Configuration); <br>FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); <br>RouteConfig.RegisterRoutes(RouteTable.Routes); <br>// 使api返回为jsonGlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();} <br>
這樣回傳的結果就都是json型別了,但有個不好的地方,如果回傳的結果是String型,如123,回傳的json就會變成"123";
解決的方法是自訂回傳型別(回傳型別為HttpResponseMessage)
public HttpResponseMessage PostUserName(User user) { String userName = user.userName; HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(userName,Encoding.GetEncoding("UTF-8"), "application/json") }; return result; }
方法:(萬金油法)
法一中又要改配置,又要處理返回值為String類型的json,甚是麻煩,不如就不用web api中的的自動序列化對象,自己序列化後再返回
public HttpResponseMessage PostUser(User user) { JavaScriptSerializer serializer = new JavaScriptSerializer(); string str = serializer.Serialize(user); HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result; }
方法二是我比較推薦的方法,為了不在每個介面中都重複寫那幾句程式碼,所以就封裝為一個方法這樣使用就方便多了。
public static HttpResponseMessage toJson(Object obj) { String str; if (obj is String ||obj is Char) { str = obj.ToString(); } else { JavaScriptSerializer serializer = new JavaScriptSerializer(); str = serializer.Serialize(obj); } HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result; }
方法三:(最麻煩的方法)
方法一最簡單,但殺傷力太大,所有的返回的xml格式都會被斃掉,那麼方法三就可以只讓api接口中斃掉xml,回傳json
先寫一個處理回傳的類別:
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; } }
找到App_Start中的WebApiConfig.cs文件,開啟Register(HttpConfiguration config)方法
加入下列程式碼:
var jsonFormatter = new JsonMediaTypeFormatter(); config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
其實web api會自動把回傳的物件轉換為xml和json兩種格式並存的形式,方法一與方法三是斃掉了xml的返回,而方法二是自訂返回。
以上就是C# web api回傳類型設定為json的兩種方法的內容,更多相關內容請關注PHP中文網(www.php.cn)!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

使用 C# 的 Active Directory 指南。在這裡,我們討論 Active Directory 在 C# 中的介紹和工作原理以及語法和範例。

多線程和異步的區別在於,多線程同時執行多個線程,而異步在不阻塞當前線程的情況下執行操作。多線程用於計算密集型任務,而異步用於用戶交互操作。多線程的優勢是提高計算性能,異步的優勢是不阻塞 UI 線程。選擇多線程還是異步取決於任務性質:計算密集型任務使用多線程,與外部資源交互且需要保持 UI 響應的任務使用異步。
