Content negotiation in ASPNET Core
April 19, 2016 by Anuraj
C# ASPNET5 ASPNET Core Web API
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 :)
Copyright © 2024 Anuraj. Blog content licensed under the Creative Commons CC BY 2.5 | Unless otherwise stated or granted, code samples licensed under the MIT license. This is a personal blog. The opinions expressed here represent my own and not those of my employer. Powered by Jekyll. Hosted with ❤ by GitHub