溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使WebAPI返回JSON格式的數(shù)據(jù)

發(fā)布時間:2020-12-05 11:42:55 來源:億速云 閱讀:267 作者:小新 欄目:編程語言

這篇文章主要介紹如何使WebAPI返回JSON格式的數(shù)據(jù),文中介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們一定要看完!

在RestFul風(fēng)格盛行的年代,對接接口大多數(shù)人會選擇使用JSON,XML和JSON的對比傳送(),看看這位博主是怎么說的,雖然最后沒有說完,我想大概也能略微解決心中的疑惑。

1.其實要想讓W(xué)ebAPI 返回JSON格式的數(shù)據(jù)很簡單,只要在ConfigureWebapi方法中配置一下即可。此前需要引用兩個命名空間。

using Newtonsoft.Json.Serialization;using System.Linq;

2.核心代碼如下:

var json = config.Formatters.JsonFormatter;// 解決json序列化時的循環(huán)引用問題json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器config.Formatters.Remove(config.Formatters.XmlFormatter);//設(shè)置序列化方式為駝峰命名法var jsonFormatter = config.Formatters.OfType<System.Net.Http.Formatting.JsonMediaTypeFormatter>().First();
 jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();//  Web API 路由config.MapHttpAttributeRoutes();

完整代碼如下:

        /// <summary>/// 配置WebApi/// </summary>/// <param name="app"></param>public void ConfigureWebapi(IAppBuilder app)
        {//創(chuàng)建一個HTTP的實例配置var config = new HttpConfiguration();var json = config.Formatters.JsonFormatter;// 解決json序列化時的循環(huán)引用問題json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器            config.Formatters.Remove(config.Formatters.XmlFormatter);//設(shè)置序列化方式為駝峰命名法var jsonFormatter = config.Formatters.OfType<System.Net.Http.Formatting.JsonMediaTypeFormatter>().First();
            jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();//  Web API 路由            config.MapHttpAttributeRoutes();//映射路由            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );//將配置注入OWIN管道中            app.UseWebApi(config);
        }

3.接下來讓我們來測試一下,添加一個名為ProductController的Controller,刪掉所有的方法,添加一個GetProductList方法,代碼如下:

       [HttpGet]public HttpResponseMessage GetProduct()
        {var product = new { id = 1, name = "三星王炸" };

            HttpResponseMessage result = new HttpResponseMessage();
            result.Content = new StringContent(JsonConvert.SerializeObject(product), Encoding.GetEncoding("UTF-8"), "application/json");return result;
        }

4.在瀏覽器中輸入http://localhost:27650/api/product/GetProduct ,輸出結(jié)果為

如何使WebAPI返回JSON格式的數(shù)據(jù)

5.我們發(fā)現(xiàn)如果在瀏覽器中輸入http://localhost:27650/api/product 同樣也可以獲得返回值,讓我們來簡單改造一下重新再寫一個新方法

        [HttpGet]public HttpResponseMessage GetProduct2(string id)
        {var product = new { id = id, name = "三星王炸" };

            HttpResponseMessage result = new HttpResponseMessage();
            result.Content = new StringContent(JsonConvert.SerializeObject(product), Encoding.GetEncoding("UTF-8"), "application/json");return result;
        }

6.在瀏覽器中輸入http://localhost:27650/api/product?id=3 和 http://localhost:27650/api/product 得到的結(jié)果分別為

如何使WebAPI返回JSON格式的數(shù)據(jù)如何使WebAPI返回JSON格式的數(shù)據(jù)

為什么會出現(xiàn)這種現(xiàn)象呢,大家看看我們開始在配置WebAPI的路由規(guī)則,規(guī)則是api/{controller}/{id} ,也就是說此規(guī)則不會去匹配action的名稱,而是根據(jù)傳入的參數(shù)類型和個數(shù)來決定的。

如何使WebAPI返回JSON格式的數(shù)據(jù)

7.那么如何讓W(xué)ebAPI 根據(jù)方法名稱來匹配呢,讓我們來修改一下路由規(guī)則,代碼如下:

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

8.讓我們再測試一下,瀏覽器中輸入http://localhost:27650/api/product,看一下效果。

如何使WebAPI返回JSON格式的數(shù)據(jù)

再輸入http://localhost:27650/api/product/GetProduct 和 http://localhost:27650/api/product/GetProduct?id=5,發(fā)現(xiàn)兩個返回的結(jié)果一樣,說明訪問的是同一個方法。

如何使WebAPI返回JSON格式的數(shù)據(jù)如何使WebAPI返回JSON格式的數(shù)據(jù)

再輸入http://localhost:27650/api/product/GetProduct2 和 http://localhost:27650/api/product/GetProduct2?id=6

結(jié)果:

如何使WebAPI返回JSON格式的數(shù)據(jù)

如何使WebAPI返回JSON格式的數(shù)據(jù)

測試通過。

以上是“如何使WebAPI返回JSON格式的數(shù)據(jù)”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對大家有幫助,更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI