Formatters In ASP.NET Core 2.0 Web API

Problem

How to accept and return the data in different formats in ASP.NET Core Web API.

Solution

In the previously created CRUD sample, update the Startup class to add input and output formatters for XML.

Try a GET request with "Accept" header of application/xml.


Try a POST request with Content-Type header of application/xml.


Discussion

The framework uses JSON by default to serialize the input and format responses containing custom models. We can configure the formatters for both, input (to serialize incoming data) and output (to format responses) in AddMvc() method, using InputFormatters and OutputFormatters collections.

Content Negotiation

To receive the data from the server, a client will specify the format it can process in Accept HTTP header. If the server has a suitable formatter, it will use it to format the response. This process is known as content negotiation.

If a suitable formatter doesn’t exist, the framework will use the default JSON formatter. You could configure the server to return 406 (Not Acceptable) status code response instead,

When sending a data to server, Content-Type header specifies the type of data in HTTP body. If a suitable input formatter is not se tup, the Server will return 415 (Unsupported Media Type) response. To demonstrate this, comment out the line that adds input formatter and try POST,



Removing Formatters

You could remove the default formatters as well, e.g. by default 204 (No Content) status code is returned for null responses. You could remove the default formatter for this behaviour, which will return 200 (OK) instead.

Format Filter

An alternate method of content negotiation and specifying the format of data client can accept is that you use [FormatFilter] filter attribute and have format (e.g. XML) in URL

However, for this to work you need to add media type mapping when configuring MVC

Now you could make a request with format in URL



Source Code

GitHub