C#webapi返回類型設(shè)置為json的方法有哪些-創(chuàng)新互聯(lián)

本篇內(nèi)容主要講解“C# web api返回類型設(shè)置為json的方法有哪些”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“C# web api返回類型設(shè)置為json的方法有哪些”吧!

成都創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:網(wǎng)站設(shè)計(jì)、成都網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的陽曲網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!

web api寫api接口時(shí)默認(rèn)返回的是把你的對象序列化后以XML形式返回,那么怎樣才能讓其返回為json呢,下面就介紹兩種方法:
方法一:(改配置法)

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


復(fù)制代碼 代碼如下:


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



修改后:


復(fù)制代碼 代碼如下:


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



這樣返回的結(jié)果就都是json類型了,但有個(gè)不好的地方,如果返回的結(jié)果是String類型,如123,返回的json就會(huì)變成"123";

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


復(fù)制代碼 代碼如下:


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中的的自動(dòng)序列化對象,自己序列化后再返回


復(fù)制代碼 代碼如下:


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



方法二是我比較推薦的方法,為了不在每個(gè)接口中都反復(fù)寫那幾句代碼,所以就封裝為一個(gè)方法這樣使用就方便多了。


復(fù)制代碼 代碼如下:


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格式都會(huì)被斃掉,那么方法三就可以只讓api接口中斃掉xml,返回json

先寫一個(gè)處理返回的類:


復(fù)制代碼 代碼如下:


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)方法

添加以下代碼:


復(fù)制代碼 代碼如下:


var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));



添加后代碼如下:


復(fù)制代碼 代碼如下:


public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));
}



方法三如果返回的結(jié)果是String類型,如123,返回的json就會(huì)變成"123",解決方法同方法一。

其實(shí)web api會(huì)自動(dòng)把返回的對象轉(zhuǎn)為xml和json兩種格式并存的形式,方法一與方法三是斃掉了xml的返回,而方法二是自定義返回。

PS:關(guān)于json操作,這里再為大家推薦幾款比較實(shí)用的json在線工具供大家參考使用:

在線JSON代碼檢驗(yàn)、檢驗(yàn)、美化、格式化工具:
http://tools.jb51.net/code/json

JSON在線格式化工具:
http://tools.jb51.net/code/jsonformat

在線XML/JSON互相轉(zhuǎn)換工具:
http://tools.jb51.net/code/xmljson

json代碼在線格式化/美化/壓縮/編輯/轉(zhuǎn)換工具:
http://tools.jb51.net/code/jsoncodeformat

在線json壓縮/轉(zhuǎn)義工具:

http://tools.jb51.net/code/json_yasuo_trans

C語言風(fēng)格/HTML/CSS/json代碼格式化美化工具:
http://tools.jb51.net/code/ccode_html_css_json

到此,相信大家對“C# web api返回類型設(shè)置為json的方法有哪些”有了更深的了解,不妨來實(shí)際操作一番吧!這里是創(chuàng)新互聯(lián)建站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

當(dāng)前文章:C#webapi返回類型設(shè)置為json的方法有哪些-創(chuàng)新互聯(lián)
本文路徑:http://muchs.cn/article42/cshcec.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作手機(jī)網(wǎng)站建設(shè)、定制開發(fā)用戶體驗(yàn)、品牌網(wǎng)站制作商城網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設(shè)計(jì)