Asp.Net WebAPI配置接口返回數據類型爲Json格式

1、默認狀況下WebApihtml

對於沒有指定請求數據類型類型的請求,返回數據類型爲Xml格式json

例如:從瀏覽器直接輸入地址,或者默認的XMLRequest,或者AngularJs的get請求等。跨域

對於有循環引用的也會拋出異常「「ObjectContent`1」類型未能序列化內容類型「application/xml; charset=utf-8」的響應正文。」瀏覽器

 

2、設置返回格式爲Json數據app

1.修改配置,這對全部的接口都生效post

找到Global.asax文件,在Application_Start()方法中添加一句: spa

GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear()

2.針對某一個接口設置.net

解決的方法是自定義返回類型(返回類型爲HttpResponseMessage) code

 
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; 
} 

 

更多:orm

Asp.Net WebApi 項目及依賴整理

Asp.Net WebApi+Microsoft.AspNet.WebApi.Core 啓用CORS跨域訪問

使Asp.net WebApi支持JSONP和Cors跨域訪問

自定義序列化處理:www.cnblogs.com/acles/archive/2013/06/21/3147667.html

相關文章
相關標籤/搜索