In this Video, I am going to discuss Content Negotiation in Web API with Examples. Please read our previous Video where we discussed ASP.NET Web API Service using the SQL Server database. From the rest architecture point of view, it is very important to understand the concept of ASP.NET Web API Content Negotiation. As part of this Video, we are going to discuss the following important concepts related to Content Negotiation.
How to Content Negotiation in Web API?. The Complete ASP.NET Web API Developer Course 2023 [Videos].
- What is Content Negotiation and its needed in Rest Services?
- How does the Web API Framework know in which format the client expects the response?
- Understanding the Accept and Content-Type headers in a request.
- Example to implement Content Negotiation in ASP.NET Web API Application.
- How to request data in JSON Format?
- How to request data in XML Format?
- What does the Web API Framework do when we request data in a specific format?
What is Content Negotiation and its needed in Rest Services?
We know that there are three pillars of the internet and they are:
- The Resource
- The URL
- The Representation
The first two are (i.e. the resource and the URL) very straightforward but the last one (i.e. the representation) is a little confusing to understand. Representation is very important in the modern web. Why? Because people are currently not only using Desktop computers to browse the web, but they also are using various types of devices (tab, mobile, etc.) to consume web applications. And the important and interesting fact is that all these various devices expect the data in various formats.
For example, a few clients want the data in normal HTML while some of them want the data in a normal text format. Others may need the data in JSON format and still some other wants the data in XML format.
Content Negotiation Definition:
We can define Content Negotiation as “the process of selecting the best representation for a given response when there are multiple representations available”.
One of the standards of the REST service is that the client should have the ability to decide in which format they want the response – whether they want the response in XML or JSON etc. This is called Content Negotiation.
Now, the fact should be clear that “ASP.NET Web API Content Negotiation” means the client and server can negotiate. Always It is not possible to return data in the requested format by the Server. Thats why it is called negotiation, not demand. In such cases, the Web API Server will return the data in the default format. Now the question that should come to your mind is, how the server knows or identifies in which format that client wants the response? Let us understand this in detail.
How does the Web API Framework (Server) know in which format the client wants the response?
This is done by checking the below headers of the request object.
- Content-type: The content-type header value request to the Web API Server to represent data in this format. The values for Content-type includes “application/json“, “application/xml“, etc.
- Accept: The Accept header value specifies the media types which are acceptable for the response, such as “application/json” and “application/xml” or any other custom media type such as “application/vnd.dotnettutorials.employees+xml“.
- Accept-Charset: The Accept-Charset header specifies which character sets are acceptable, such as UTF-8 or ISO 8859-1.
- Accept-Encoding: The Accept-Encoding header specifies which content encodings are acceptable, such as gzip.
- Accept-Language: The Accept-Language header specifies the preferred natural language support, such as “en-us“.
Understanding the Accept and Content-Type headers:
A request that is sent to the server includes Accept and Content-Type headers. Using the Accept header the client can specify the format for the response. For example
Content-Type: application/xml returns XML
Content-Type: application/json returns JSON
Accept: application/xml returns XML
Accept: application/json returns JSON
Depending on the Accept header and Content-Type value in the request object, the server sends the response. This is called Web API Content Negotiation.
Example to understand Content Negotiation in ASP.NET Web API.
In this Video, we are going to work with the same example that we started in our previous Video where we discussed the step-by-step procedure of
Below is our controller
How to Request Web API Service to Return Data in JSON Format?
The JSON format is currently the most popular format of data representation. So, first, we will see how to return the data in JSON format from the ASP.NET Web API Application. We are going to use a tool called Fiddler to test the Web API services. So please read before proceeding to this Video. Even you can also use Postman to test the services.
Example: Get the Employee details by Employee Id
Now we are going to make a request to the server to get the employee details in JSON Format. So, we are going to make a request to the api/employees/1 URL. Please have a look at the below image. Here is our HTTP header information to get the employee details whose id is 1. Select the Composer Tab. Then select the HTTP verb as “GET“. Then provide the URL and click on the Execute button as shown in the below image.
Here you can see that we did not set the Content-Type header value to request the data in JSON format but the Web API returning the data in JSON format. The reason is by default the Web API will return the data in JSON format if we do not specify any “Content-Type” header in the request. See the following output.
And obviously, we can also modify the header value like the following to get the data in JSON format.
Both requests will give us the same output.
How to Request ASP.NET Web API Server to return the data in XML format?
Now, we will request the ASP.NET Web API Service to return the data in XML format. Now to get the data in XML format we need to set the Content-Type header of the HTTP Request to application/xml in the request as shown in the below image.
Once you click on the execute button, you will get the data in XML format as shown in the below image.
The above two are the formats (i.e. JSON and XML) that ASP.NET Web API supports by default. If you want other than these two types of representations then you need to implement a media type formatter in the Web API, which we will discuss in our upcoming Videos.
Understanding Accept Header in HTTP Request:
In our previous examples, we saw how a content-type header works with HTTP Requests. Now, we will understand the “Accept” header of the HTTP Request.
Request With Accept Header:
As we have specified three different representations in the accept header, the ASP.NET Web API Framework is going to send the response in JSON format. So, when you click on the Execute button, you will get the following response.
Understanding Accept-Language header
In the Accept-Language header, we can specify the preferred language that we want to get from the Web API application. The Accept-Language header is used as Accept-Language: en-IN, en-US
The above Accept-Language header indicates that my first choice of language is Indian English but if that is not possible then please give me US English and if that is not possible then please provide the data in the default language.
So Web API Content negotiation is a mechanism, or algorithm, used to determine, based on the clients request, which media type formatter is going to be used to return an API response. In the next Video, we will discuss what is media type formatter and how it works with some examples.
What does the Web API Framework do when we request data in a specific format?
The controller action method first generates the data that we want to send to the client. For example, if we have asked for the list of employees. The Web API Controller action method generates the list of employees and hands the data to the Web API pipeline which then looks at the Accept header value, and depending on the format that the client has requested, the Web API Framework will choose the appropriate formatter. For example, if the client has requested the data in XML format, then Web API uses XML Formatter. similarly, if the client has requested the data in JSON format, then Web API uses JSON Formatter. These formatters are called Media Type Formatters.
ASP.NET Web API is greatly extensible. This means we can also plug in our own formatters, for custom formatting the data. Multiple values can also be specified for the Accept header. In this case, the server picks the first formatter which is a JSON formatter, and formats the data in JSON.
You can also specify a quality factor. In the example below, XML has a higher quality factor than JSON, so the server uses XML formatter and formats the data in XML.
If you dont specify the Accept header in the request then by default the Web API returns the data in JSON format.
When the response is sent to the client, notice that the Content-Type header of the response is set to the appropriate value. For example, if the client has requested for application/xml, then the server sends the data in XML format and also sets the Content-Type=application/xml.
Role of Media Type Formatter:
The Web API uses the formatters for both request and response messages. When the client makes a request to the server, the client has to 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 the .NET type to JSON, XML, etc.
We can also easily change the serialization settings of these formatters. For example, if we want the JSON data to be properly indented and use a camel case instead of a Pascal case for property names, all we have to do is modify the serialization settings of JSON formatters as shown below. With our example, this code goes in WebApiConfig.cs file in the App_Start folder.
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver= new CamelCasePropertyNamesContractResolver();