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

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

高洛峰
高洛峰原創
2017-01-18 09:29:481153瀏覽

web api寫api介面時預設回傳的是把你的物件序列化後以XML形式返回,那麼怎樣才能讓其返回為json呢,下面就介紹兩種方法: 
方法一:(改配置法) 

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

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

修改後: 

protected void Application_Start() 
{ 
AreaRegistration.RegisterAllAreas(); 
WebApiConfig.Register(GlobalConfiguration.Configuration); 
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
RouteConfig.RegisterRoutes(RouteTable.Routes); 
// 使api返回为json 
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); 
}

這樣回傳的結果就都是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)方法 

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

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

更多C# web api回傳類型設定為json的兩種方法相關文章請關注PHP中文網!

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