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