The Web API writes the API interface when it returns

Source: Internet
Author: User

When the Web API writes API interface, the default return is to serialize your object and return it as XML, so how do you get it back as JSON, and here are two ways to do it:
Method One: (Change the Configuration method)

Locate the Global.asax file and add a sentence in the Application_Start () method:

Copy CodeThe code is as follows:
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();


After modification:

Copy CodeThe code is as follows:
protected void Application_Start ()
{
Arearegistration.registerallareas ();
Webapiconfig.register (globalconfiguration.configuration);
Filterconfig.registerglobalfilters (globalfilters.filters);
Routeconfig.registerroutes (routetable.routes);
Returning the API to JSON
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear ();
}


This returns the result is JSON type, but there is a bad place, if the result returned is a string type, such as 123, the returned JSON will become "123";

The workaround is to customize the return type (return type is Httpresponsemessage)

Copy CodeThe code is as follows:
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;
}

The Web API writes the API interface when it returns

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.