[Web API] Content – Type, Negotiation, and Formatters

Web API supports a couple of formatters to serialize or deserialize input/output data. A client can request what kind of data back as a response. It is called “Content Negotiation“.


1. Formatters

By default, Web API binds incoming data to CLR types (deserialization) and CLR types to output content types (serialization).

The abstract “System.Net.Http.Formatting.MediaTypeFormatter” class is a base class for formatters.

  • FormUrlEncodedMediaTypeFormatter : application/x-www-form-urlencoded
  • JsonMediaTypeFormatter : application/json
  • XmlMediaTypeFormatter : application/xml

Web API selects the formatter based on the media types provided by HTTP requests.

  • From Client: JSON, XML, HTML form
  • From Server: JSON, XML


2. Content-Type

HTTP “Content-Type” header is used to specify the MIME type for the message body.

For example, when you send “POST” or “PUT” requests, you might want to specify the message type you are sending. The “Content-Type” header is used for this purpose.


3. Content Negotiation : Accept

When a client requests a resource to a server, the client can specify the desired formats using HTTP “Accept” header.

Accept: application/json

If the client does not specify the requried type, Web API uses its default formatter to create an output. The default type is “JSON” and the formatter is “System.Net.Http.Formatting.JsonMediaTypeFormatter“. JSON can be consummed by the client JavaScript code.

If you want XML as an output, just specify “application/xml” in the “Accept” header. Web API will return xml output for you using the “XmlMediaTypeFormatter“.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s