Home > Backend Development > C#.Net Tutorial > Let WebAPI return data in JSON format tutorial

Let WebAPI return data in JSON format tutorial

零下一度
Release: 2018-05-21 11:10:03
Original
10614 people have browsed it

In the era when the RestFul style is prevalent, most people will choose to use JSON, XML and JSON comparison transmission () for docking interfaces. Let’s see what this blogger said. Although he didn’t finish it in the end, I think it’s probably the same. It can slightly resolve the doubts in my mind.

1. In fact, it is very simple to make WebAPI return data in JSON format. Just configure it in the ConfigureWebapi method. Previously two namespaces needed to be referenced.

using Newtonsoft.Json.Serialization;using System.Linq;
Copy after login

2. The core code is as follows:

var json = config.Formatters.JsonFormatter;// 解决json序列化时的循环引用问题json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器config.Formatters.Remove(config.Formatters.XmlFormatter);//设置序列化方式为驼峰命名法var jsonFormatter = config.Formatters.OfType<system.net.http.formatting.jsonmediatypeformatter>().First();
 jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();//  Web API 路由config.MapHttpAttributeRoutes();</system.net.http.formatting.jsonmediatypeformatter>
Copy after login

The complete code is as follows:

        /// <summary>/// 配置WebApi/// </summary>/// <param>public void ConfigureWebapi(IAppBuilder app)
        {//创建一个HTTP的实例配置var config = new HttpConfiguration();var json = config.Formatters.JsonFormatter;// 解决json序列化时的循环引用问题json.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;// 移除XML序列化器            config.Formatters.Remove(config.Formatters.XmlFormatter);//设置序列化方式为驼峰命名法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);
        }</system.net.http.formatting.jsonmediatypeformatter>
Copy after login

3 .Next let us test it, add a Controller named ProductController, delete all methods, and add a GetProductList method, the code is as follows:

       [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;
        }
Copy after login

4. Enter http://localhost in the browser :27650/api/product/GetProduct, the output result is

Let WebAPI return data in JSON format tutorial

5. We found that if we enter http://localhost:27650/api/product in the browser, the same The return value can be obtained, let us simply transform it and write a new method

        [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;
        }
Copy after login

6. Enter http://localhost:27650/api/product?id in the browser =3 and http://localhost:27650/api/product, the results obtained are

Let WebAPI return data in JSON format tutorialLet WebAPI return data in JSON format tutorial

Why does this happen? Let’s take a look. When configuring the routing rules of WebAPI, the rule is api/{controller}/{id}, which means that this rule will not match the name of the action, but will be determined based on the type and number of parameters passed in.

Let WebAPI return data in JSON format tutorial

7. So how to make WebAPI match according to the method name? Let us modify the routing rules. The code is as follows:

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

8. Let us test it again. Enter http://localhost:27650/api/product in the browser to see the effect.

Let WebAPI return data in JSON format tutorial

Then enter http://localhost:27650/api/product/GetProduct and http://localhost:27650/api/product/GetProduct?id=5 and found The two returned results are the same, indicating that the same method is accessed.

Let WebAPI return data in JSON format tutorialLet WebAPI return data in JSON format tutorial

Then enter http://localhost:27650/api/product/GetProduct2 and http://localhost:27650/api/product/GetProduct2?id= 6

Result:

Let WebAPI return data in JSON format tutorial

Let WebAPI return data in JSON format tutorial

##The test passed.

This is just for organizing and deepening the impression in case you forget. If there is anything incorrect, please feel free to give us your advice.

The above is the detailed content of Let WebAPI return data in JSON format tutorial. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template