Monday, 31 December 2018

What is Content Negotiation?

One of the standards of the RESTful service is that, the client should have the ability to decide in which format they want the response - XML, JSON etc. A request that is sent to the server includes an Accept header. Using the Accept header the client can specify the format for the response. For example

Accept: application/xml returns XML
Accept: application/json returns JSON

Depending on the Accept header value in the request, the server sends the response.
Web API is setup by default to provide responses in either XML or JSON (JSON is default). However, as a developer you do not need to do any conversion or parsing – you simply return a strongly typed object and Web API will convert it to XML or JSON and return it to the calling client, this process is called Content Negotiation.

ASP.NET Web API is greatly extensible. This means we can also plug in our own formatters, for custom formatting the data apart from XML and JSON.
Multiple values can be specified for the Accept header. In this case, the server picks the first formatter.

Accept: application/xml,application/json

You can also specify quality factor. Higher quality factor formatter will be picked by the server.

application/xml;q=0.9,application/json;q=0.7


The formatters are used by the server for both request and response messages. When the client sends a request to the server, we set the Content-Type header to the appropriate value to let the server know the format of the data that we are sending. For example, if the client is sending JSON data, the Content-Type header is set to application/json. The server knows it is dealing with JSON data, so it uses JSON formatter to convert JSON data to .NET Type. Similarly when a response is being sent from the server to the client, depending on the Accept header value, the appropriate formatter is used to convert .NET type to JSON, XML etc.

No comments:

Post a Comment