The C # Web API return type is set to JSON in two ways

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)

void//  


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

The code is as follows:

After modification:

The code is as follows:

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)The code is as follows:
 Public Httpresponsemessage postusername (user user)

String userName = user.username; New New Stringcontent (username,encoding.getencoding ("UTF-8""Application/json ") }; return result;

Method Two: (Balm method)
Instead of using the automatic serialization object in the Web API, it is cumbersome to change the configuration in method one and to process JSON with a return value of string, and then return it after serializing itself.

The code is as follows:

Public

New JavaScriptSerializer (); string New New Stringcontent (str, encoding.getencoding ("UTF-8""Application/json "
Return

Method Two is my recommended method, in order not to repeat the code in each interface, so the encapsulation of a method so that the use of more convenient.

The code is as follows:
 Public StaticHttpresponsemessage ToJson (Object obj)
{
String str;
if(obj isString | | Obj isChar) {
STR= obj. ToString ();
}
Else
{
JavaScriptSerializer serializer =NewJavaScriptSerializer (); str =Serializer. Serialize (obj); }
Httpresponsemessage result=NewHttpresponsemessage
{
Content =NewStringcontent (str, encoding.getencoding ("UTF-8"),"Application/json")
}; returnResult
}

Method Three: (the most troublesome method)
Method One is the simplest, but the lethality is too large, all the returned XML format will be killed, then the method three can only let the API interface to kill the XML, return JSON
First write a class that handles the return:

. the code is as follows:
 Public classJsoncontentnegotiator:icontentnegotiator {Private ReadOnlyJsonmediatypeformatter _jsonformatter; PublicJsoncontentnegotiator (Jsonmediatypeformatter formatter) {_jsonformatter =formatter;}  PublicContentnegotiationresult Negotiate (type type, httprequestmessage request, ienumerable<mediatypeformatter> formatters) {varresult =NewContentnegotiationresult (_jsonformatter,NewMediatypeheadervalue ("Application/json"));returnResult } }

Locate the WebApiConfig.cs file in App_start, open the Find register (httpconfiguration config) method
Add the following code:

The code is as follows:

var New jsonmediatypeformatter (); config. Services.replace (typeofnew

Add the following code as follows:

The code is as follows:
 Public Static voidRegister (httpconfiguration config)
{
Config. Routes.maphttproute (Name:"Defaultapi", Routetemplate:"Api/{controller}/{action}/{id}", defaults:New{id = routeparameter.optional});
varJsonformatter =NewJsonmediatypeformatter (); Config. Services.replace (typeof(Icontentnegotiator),NewJsoncontentnegotiator (Jsonformatter)
);
}

Method Three if the returned result is a string type, such as 123, the returned JSON becomes "123", and the workaround is the same as method one.
In fact, the Web API will automatically convert the returned object to XML and JSON two format coexistence form, method one and method three is to kill the return of the XML, and method two is the custom return.

The C # Web API return type is set to JSON in two ways

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.