Loading

ASP.NET Web API

How to Content Negotiation in Web API?. The Complete ASP.NET Web API Developer Course 2023 [Videos].

In this article, I am going to discuss Content Negotiation in Web API with Examples. Please read our previous article 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 article, we are going to discuss the following important concepts related to Content Negotiation.

  1. What is Content Negotiation and its needed in Rest Services?
  2. How does the Web API Framework know in which format the client expects the response?
  3. Understanding the Accept and Content-Type headers in a request.
  4. Example to implement Content Negotiation in ASP.NET Web API Application.
  5. How to request data in JSON Format?
  6. How to request data in XML Format?
  7. 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:

  1. The Resource
  2. The URL
  3. 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 etcThis 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.

  1. 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.
  2. 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“.
  3. Accept-Charset: The Accept-Charset header specifies which character sets are acceptable, such as UTF-8 or ISO 8859-1.
  4. Accept-Encoding: The Accept-Encoding header specifies which content encodings are acceptable, such as gzip.
  5. 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
namespace EmployeeService.Controllers
{
public class EmployeesController : ApiController
{
public IEnumerable<Employee> Get()
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
return dbContext.Employees.ToList();
}
}
public Employee Get(int id)
{
using (EmployeeDBContext dbContext = new EmployeeDBContext())
{
return dbContext.Employees.FirstOrDefault(e => e.ID == id);
}
}
}
}
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.

How to Request Web API Service to Return Data in JSON Format?

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.

How to Request Web API Service to Return Data in JSON Format?

And obviously, we can also modify the header value like the following to get the data in JSON format.

Content Negotiation in ASP.NET Web API

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.

How to Request Web API Server to return the data in XML format?

Once you click on the execute button, you will get the data in XML format as shown in the below image.

ASP.NET Web API Content Negotiation

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.

By checking the “Accept” header value, the ASP.NET Web API understands in which formats the client wants the response. For example, if we specify that the client can understand the following representations: application/xml , application/json, text/javascript, then the Web API Service will return the data in JSON format, the reason is JSON is the default format of the Web API, although the clients first preference is the XML format. We will prove it with a small example. 

Request With Accept Header:

Please have a look at the below image. Here, we are making a request to the Web API service to get the employee details whose email id is 1. If you further notice, here we specify the Accept header value as application/xml , application/json, text/javascript. 

Understanding Accept Header in Http Request

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. 

Content Negotiation in Web API

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.

Accept: application/xml,application/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.

application/xml;q=0.8,application/json;q=0.5

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();

See All

Comments (312 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Web API / Blog

What is ASP.NET Web API Application?

In this ASP.NET Web API Tutorials series, I covered all the features of ASP.NET Web API. You will learn from basic to advance level features of ASP.NET Web API. The term API stands for “Application Programming Interface” and ASP.NET Web API is a framework provided by Microsoft which makes it easy to build Web APIs, i.e. it is used to develop HTTP-based web services on the top of .NET Framework.
3-Feb-2022 /34 /312

ASP.NET Web API / Blog

How to creat ASP.NET Web API Application using Visual Studio?

In this article, I am going to discuss the step-by-step procedure for Creating ASP.NET Web API Application. Please read our previous article before proceeding to this article where we gave an overview of the ASP.NET Web API framework. As part of this article, we ate going to discuss the following pointers.
3-Feb-2022 /34 /312

ASP.NET Web API / Blog

How to add Swagger in Web API Application?

In this article, I am going to discuss how to add Swagger in Web API Application to document and test restful Web API services. Please read our previous article where we discussed How to Create an ASP.NET Web API Application step by step before proceeding to this article as we are going to work with the same example. As part of this article, we are going to discuss the following pointers.
3-Feb-2022 /34 /312