By default, when we create a new WEBAPI project, we automatically return the data in XML format, and if we want to return the JSON data, we can set the following three ways.
1. Do not change the configuration file, in the controller's method, directly return Httpresponsemessage
Publichttpresponsemessage Returnjson () {//Initializing test ObjectsTestjsonobj T =Newtestjsonobj (); T.name="Alun"; T.address="GZ"; //obj into JSON stringJSON =Jsonconvert.serializeobject (t); //returns the number of JSON return NewHttpresponsemessage () {Content=NewStringcontent (JSON, Encoding.UTF8,"Application/json"), }; }
Testjsonobj is our test class.
The above method is more complicated, but flexible. It's a bit slow to convert objects to JSON every time.
2. In the global settings, clear all the returned formats and set the JSON. all returned XML formats will be erased.
In the Register method of the Webapiconfig class, we add the following code:
CONFIG. Formatters.clear (); config. Formatters.add (new jsonmediatypeformatter ());
This way, although it can be implemented, all conent negotiation will still occur, which will incur the following additional overhead. Because, you already know the result to return, and just want to return the JSON, other content negotiation no need.
3. In global settings, only JSON Result is returned using a custom. just let the API interface replace the XML, return the JSON
In the Register method of the Webapiconfig class, we add the following code:
var New jsonmediatypeformatter (); config. Services.replace (typeofnew jsoncontentnegotiator (Jsonformatter));
Use a custom content negotiation that returns only JSON result instead of the default content negotiation in the Web API.
This article recommends method 3 because it is easy to use.
Attention:
If the swagger is used:
When using Method 1, on the Swagger page, the description of the returned obj document is not displayed
When using method 3,swagger, the document will remain in fetching resource state.
So we use Method 2 in the test, the formal environment when using Method 3, do a judgment on it, as follows:
// set back JSON if (cpublicattribute.testenviroment) { CONFIG. Formatters.clear (); Config. Formatters.add (new jsonmediatypeformatter ()); } Else { varnew jsonmediatypeformatter (); Config. Services.replace (typeofnew jsoncontentnegotiator (Jsonformatter));
C # WEBAPI returns JSON