ASP.NET Core does support out of the box JSON, XML, or plain text formatters based on the ACCEPT Header. In this post, I’ll explain how to specify other formatters and return them based on the ACCEPT Header. As an example, I use a CSV formatter to return a CSV formatter. A controller method returns the format based on the ACCEPT Header which is specified by the client. This can be very useful in cases where you need to export your data to Excel, and the use of more formats makes your application more accessible.
HTTP ACCEPT Header
The Accept request-header field can be used to specify certain media types which are acceptable for the response. The response media type can differ from the request media type. By sending ACCEPT Headers you let the server know how the client likes the response to be formatted. If the server is able to return the specified formatting. It will respond in that format.
At the server side, you are able to specify what the response types are you want to deliver to your clients. The default accepted headers are JSON, XML, and plain text. Adding extra response types can be done by configuring a formatter in the startup. When a client sends one or more ACCEPT Headers the server can write the response in the best-matched format.
Add a CSV Formatter
A CSV formatter can be used where you have objects that you want to return in a CSV format to use in for example Excel. Normally the client needs an array of elements. To let the server know that it wants a CSV format the client adds an
Implement a CSV Formatter
A text output formatter has to derive from
TextOutputFormatter. By setting the
SupportedMediaTypes you tell what types of media you support. When exporting to In this case
CanWriteType method does return true if the type that is returned is supported for serialization. The ACCEPT Header must contain
text/csv and the return type must be of the type
Configure the Formatter
To use the formatter you have to configure it at startup. This is done by adding the formatter to the output formatters in the
Adding your own formatters is very easy when you know how it works. In cases you have to export your data to Excel, a CSV formatter makes that a very simple task if you have implemented and registered the formatter.