Content Negotiation in Web API

Content negotiation is the process of selecting the best representation (format) of a resource for a client, based on the client's request headers. It's commonly used in ASP.NET Web API and ASP.NET Core Web API.

 

When a client sends a request to a Web API, it can specify which formats it can accept using the Accept HTTP header:

OR

The Web API inspects the header and returns the response in the appropriate format (e.g., JSON or XML).

 

 

 

 

ASP.NET Core
ASP.NET Core supports JSON by default using System.Text.Json. You can also add support for XML and other formats.
Step 1: Enable XML in Startup.cs (if using XML)

 

Now, based on the request's Accept header, the API will return JSON or XML.

 

 

 

Requesting JSON By Client


 

Requesting XML By Client

 

 

 

Server Response Based on Accept Header
Accept Header           Response Format
application/json        JSON
application/xml         XML (if supported)
text/plain                   Plain text (if supported)
*/* or omitted           Default (usually JSON)

 

 

If the server can't match any of the requested formats, it returns 406 Not Acceptable (only if you explicitly configure it to do so).

Can customize this behavior using MvcOptions.ReturnHttpNotAcceptable = true.

 

 


Related Question