Formatters in ASP.NET Core 2.0 Web API

Problem

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

Solution

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

Try a GET request with Accept header of application/xml:

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

Discussion

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

Content Negotiation

To receive data from the server, 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 formatted doesn’t exist, framework will use the default JSON formatter. You could configure the server to return 406 (Not Acceptable) status code response instead:

When sending data to server, Content-Type header specifies the type of data in HTTP body. If a suitable input formatter is not setup, 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 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: https://github.com/TahirNaushad/Fiver.Api.Formatters

Leave a Reply