web-api
  1. web-api-working-with-media-type-formatters

Working with Media Type Formatters - (Web API Content Negotiation)

Web API content negotiation is the process by which a client and a server determine the best representation of a resource to use in a given context. Media type formatters are an important part of content negotiation in Web API. In this tutorial, we'll discuss what media type formatters are and how to work with them in Web API.

Syntax

There is no specific syntax for working with media type formatters in Web API.

Example

Suppose you have an action method in your Web API controller that returns an object myObject in JSON format:

public IHttpActionResult GetMyObject()
{
    MyObject myObject = new MyObject();
    // populate myObject

    return Json(myObject);
}

In this example, Json is a media type formatter that serializes the myObject object into JSON format.

Explanation

Media type formatters are used to convert data between the format that is used to transmit data over the wire and the format that is used in your application code. When you return an object from a Web API action method, the object must be serialized into a format, such as JSON or XML, that can be transmitted over the wire. Similarly, when you receive data from a client, it must be deserialized from its transmitted format into the format used by your application.

Web API comes with several built-in media type formatters, such as JsonMediaTypeFormatter, XmlMediaTypeFormatter, and FormUrlEncodedMediaTypeFormatter. You can also create your own custom media formatters if needed.

Use

Media type formatters are a critical part of content negotiation in Web API. They allow your Web API to communicate with clients in a variety of formats, such as JSON, XML, and form-encoded data.

Important Points

Here are some important points to keep in mind when working with media type formatters in Web API:

  • Web API comes with several built-in media type formatters, such as JsonMediaTypeFormatter, XmlMediaTypeFormatter, and FormUrlEncodedMediaTypeFormatter.
  • You can create custom media type formatters if needed.
  • When returning data from a Web API action method, the media type formatter used depends on the Accept header sent by the client.
  • When receiving data from a client, the media type formatter used depends on the Content-Type header sent by the client.

Summary

In this tutorial, we discussed media type formatters and their role in content negotiation in Web API. We covered syntax, examples, explanation, use, and important points of using media type formatters to convert data between the format used to transmit data over the wire and the format used in your application code. With this knowledge, you can work with media type formatters in Web API to provide responsive and flexible data interchange between your API and clients.

Published on: