Let Webapi return data instance tutorial in JSON format

Source: Internet
Author: User
In the age of restful style, the docking interface most people will choose to use Json,xml and JSON comparison transmission (), to see what the blogger said, although in the end, I think I can probably slightly solve the doubts.

1. In fact, to let WEBAPI return JSON format data is very simple, as long as the Configurewebapi method is configured. Previously, a reference of two namespaces was required.

Using newtonsoft.json.serialization;using System.Linq;

2. The core code is as follows:

var json = config. formatters.jsonformatter;//the JSON for circular reference problems when JSON serialization is resolved. serializersettings.referenceloophandling = newtonsoft.json.referenceloophandling.ignore;// Removes the XML serializer Config.Formatters.Remove (config. Formatters.xmlformatter);//Set the serialization method to the Hump naming method 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>///configuration webapi///</summary>///<param name= "app" ></param>public void Configure Webapi (Iappbuilder app) {//Create an instance of HTTP config var config = new httpconfiguration (); var json = config. formatters.jsonformatter;//the JSON for circular reference problems when JSON serialization is resolved. serializersettings.referenceloophandling = newtonsoft.json.referenceloophandling.ignore;//Removes the XML Serializer config. Formatters.remove (config. Formatters.xmlformatter);//Set the serialization method to the Hump naming method var jsonformatter = config. Formatters.oftype<system.net.http.formatting.jsonmediatypeformatter> ().            First ();            JsonFormatter.SerializerSettings.ContractResolver = new Camelcasepropertynamescontractresolver ();//Web API Routing Config. Maphttpattributeroutes ();//Map Route CONFIG.                Routes.maphttproute (Name: "Defaultapi", Routetemplate: "Api/{controller}/{id}", defaults:new {id = routeparameter.optional});//inject configuration into the app in the Owin pipeline.    Usewebapi (config);    } 

3. Next let's test, add a controller named Productcontroller, delete all the methods, add a Getproductlist method, the code is as follows:

       [Httpget]public httpresponsemessage getproduct ()        {var product = new {id = 1, name = "Samsung King Fried"};            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 and the output is

5. We found that if you enter http://localhost:27650/api/product in the browser, you can also get the return value, let's simply remodel and re-write a new method

        [Httpget]public httpresponsemessage GetProduct2 (string id)        {var product = new {id = id, name = "Samsung King Fried"};            Httpresponsemessage result = new Httpresponsemessage ();            Result. Content = new Stringcontent (Jsonconvert.serializeobject (product), encoding.getencoding ("UTF-8"), "Application/json" ); return result;        }

6. The results of entering http://localhost:27650/api/product?id=3 and http://localhost:27650/api/product in the browser are

Why does this happen, everybody see we start to configure WEBAPI routing rules, the rule is api/{controller}/{id}, which means that this rule does not match the name of the action, but depends on the type and number of arguments passed in.

7. So how do I get webapi to match 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 us test again, the browser input http://localhost:27650/api/product, look at the effect.

Re-enter http://localhost:27650/api/product/GetProduct and http://localhost:27650/api/product/GetProduct?id= 5, the two returned results are found, stating that the same method is being accessed.

Re-enter HTTP://LOCALHOST:27650/API/PRODUCT/GETPRODUCT2 and http://localhost:27650/api/product/GetProduct2?id=6

Results:

Test passed.

This is only for finishing, to deepen the impression, in case you forget. If there is an incorrect place, welcome to feel free.

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.