Introduction
In this article we describe how to implement the content negotiation in the ASP.NET Web API.
Content negotiation is used to determine the best way for representing a response when there are multiple possible representations available. It finds the representation for sending the response. There are some mechanisms for content negotiation; they are:
- Accept: It is defined as the media type that are acceptable for the response. For example JSON and XML.
- Accept-Charset: It is defined as the acceptable character set for the response. For example UTF-8 etcetera.
- Accept Encoding: It is defined as the type of content encoding that are acceptable for the response. For example gzip.
- Accept Language: It is defined as the preferable language for the response.
Serialization
Serialization means to serialize the value by the pipeline, such as the value that is given by the Web API and the the pipeline that serializes that value and used as a response.
Let's see an example of the controller:
public Item GetItemById(int sn)
{
var mat = items.FirstOrDefault((m) => m.id ==sn);
if (mat == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return mat;
}
The client might send the request:
GET http://localhost:21374/api/item/1/Http/1.1Host:localhost:21374
Accept: ApplicationException/json,text/javascript
The server gives the response:
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 56
Connection: Close
{"sn":1,"Name":"apple","type":"fruit","cost":100}
The object of the HttpResponseMessage can be returned by the controller. If there is a need for a CLR object in the response then we invoke the CreateResponse method.
public HttpResponseMessage GetItem(int sn)
{
var item = items.FirstOrDefault(m => m.id == sn);
if (item == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return Request.CreateResponse(HttpStatusCode.OK, item);
}

Join the conversation! Your thoughts help the community grow.