首頁  >  文章  >  後端開發  >  C# web api傳回類型設定為json的兩種方法

C# web api傳回類型設定為json的兩種方法

黄舟
黄舟原創
2017-01-19 10:39:391219瀏覽

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

方法三如果回傳的結果是String類型,如123,則傳回的json就會變成"123",解法同方法一。 


其實web api會自動把回傳的物件轉換為xml和json兩種格式並存的形式,方法一與方法三是斃掉了xml的返回,而方法二是自訂返回。

以上就是C# web api回傳類型設定為json的兩種方法的內容,更多相關內容請關注PHP中文網(www.php.cn)!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn