WebAPI construction (2) allows WebAPI to return JSON data, webapijson

Source: Internet
Author: User

WebAPI construction (2) allows WebAPI to return JSON data, webapijson

In the era of RestFul style, most people will choose to use JSON, XML and JSON communication interface (http://blog.csdn.net/liaomin416100569/article/details/5480825), see what the blogger said, although not finished at the end, I think it can also slightly solve my doubts.

1. In fact, to make WebAPI return JSON-format data, you only need to configure it in the ConfigureWebapi method. Two namespaces need to be referenced before.

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

2. The core code is as follows:

 

Var json = config. formatters. jsonFormatter; // solves the circular reference problem during json serialization. json. serializerSettings. referenceLoopHandling = Newtonsoft. json. referenceLoopHandling. ignore; // remove the XML serializer config. formatters. remove (config. formatters. xmlFormatter); // set the serialization method to var jsonFormatter = config. formatters. ofType <System. net. http. formatting. jsonMediaTypeFormatter> (). first (); jsonFormatter. serializerSettings. contractResolver = new CamelCasePropertyNamesContractResolver (); // Web API route config. mapHttpAttributeRoutes ();

The complete code is as follows:

/// <Summary> /// configure WebApi /// </summary> /// <param name = "app"> </param> public void ConfigureWebapi (IAppBuilder app) {// create an HTTP instance and configure var config = new HttpConfiguration (); var json = config. formatters. jsonFormatter; // solves the circular reference problem during json serialization. json. serializerSettings. referenceLoopHandling = Newtonsoft. json. referenceLoopHandling. ignore; // remove the XML serializer config. formatters. remove (config. formatters. xmlFormatter); // set the serialization method to var jsonFormatter = config. formatters. ofType <System. net. http. formatting. jsonMediaTypeFormatter> (). first (); jsonFormatter. serializerSettings. contractResolver = new CamelCasePropertyNamesContractResolver (); // Web API route config. mapHttpAttributeRoutes (); // map the route config. routes. mapHttpRoute (name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new {id = RouteParameter. optional}); // inject the configuration into the app in the OWIN pipeline. useWebApi (config );}

3. Next let's test it. Add a Controller named ProductController, delete all the methods, and add a GetProductList method. The Code is as follows:

[HttpGet] public HttpResponseMessage GetProduct () {var product = new {id = 1, name = "Samsung King"}; HttpResponseMessage result = new HttpResponseMessage (); result. content = new StringContent (JsonConvert. serializeObject (product), Encoding. getEncoding ("UTF-8"), "application/json"); return result ;}

 

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

5. We found that if you enter http: // localhost: 27650/api/product in the browser, the returned value can also be obtained. Let's 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 ;}

6. In the browser, enter http: // localhost: 27650/api/product? Id = 3 and http: // localhost: 27650/api/product

Why does this happen? Let's take a look at the configuration of web api routing rules, the rule is api/{controller}/{id}, that is, this rule does not match the action name, it is determined by the input parameter type and number.

7. How can we make the WebAPI match based on the method name? Let's modify the routing rule. The Code is as follows:

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

 

8. Let's test it again. Enter http: // localhost: 27650/api/product in the browser to check the effect.

Enter http: // localhost: 27650/api/product/GetProduct and http: // localhost: 27650/api/product/GetProduct? Id = 5. If the two returned results are the same, the method is accessed.

Enter http: // localhost: 27650/api/product/GetProduct2 and http: // localhost: 27650/api/product/GetProduct2? Id = 6

Result:

Test passed.

Here, we will only sort out and deepen our impressions to prevent you from forgetting them. If there are any errors, please kindly advise.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.