Posted by Anuraj on Tuesday, April 19, 2016
Content negotiation as “the process of selecting the best representation for a given response when there are multiple representations available”. Content negotiation takes place when browser or other HTTP-client requests server what content formats it accepts. HTTP-client uses Accept header to list all formats it can understand. By default ASP.NET Core returns responses as JSON, even if the client sends accept header with application/xml value.
Here is my code, which returns a list of products and I didn’t mentioned anything about the format. But it returns JSON output.
It is because Xml formatters are not included as part of the Microsoft.AspNet.Mvc package. To return the response as XML you need to add reference of XML formatters. Here is the project.json file.
And here is the code which enables XML formatters, inside the Startup.cs file.
Now if your client sends a request with accept header, it will return XML instead of JSON.
And you can get JSON output if you change the accept header to application/json instead of application/xml.
Happy Programming :)