Formatters and API Controllers

In this lesson, we will learn how to send complex content to action methods like plain-text, XML, and JSON in the request body.

Body content requested in a way different from the form parameters is processed by software modules called formatters. Formatters are not invoked during the various steps of a standard recursive procedure like binders. Instead, they are monolithic chunks of software that receive the type of their target parameters as input and directly return the whole object tree needed to fill these target parameters.

There is no way of sending something different from form fields in the request body without using JavaScript. The only way to send different content is an AJAX call. Therefore, formatters are used only by action methods that respond to AJAX calls.

Built-in formatters

The right formatter is chosen according to the Content-Type request header. ASP.NET Core has the following built-in formatters:

Content-Type Formatter
text/plain Text formatter that handles text/plain responses
application/json or text/json JSON formatter that attempts to convert the JSON content into the type of the target parameter
application/xml or text/xml JSON formatter that attempts to convert the XML content into the type of the target parameter

By default, the XML formatter is not enabled. It can be enabled in the startup.cs file as shown below:

For the text/plain formatter there is just an output formatter that is a formatter that creates text/plain responses. There is no input formatter that might fill in action method parameters. The reason is that the corresponding input formatter would not be very useful, since text can be received in a JSON object.

The JSON formatter uses the .NET JsonSerializer class to try to transform JSON into a target type. We can supply custom options of the JsonSerializer used by the JSON formatter in the startup.cs file as shown below:

Get hands-on with 1200+ tech skills courses.