How would you write a custom output formatter to support a non-standard format, like CSV, for specific endpoints?
Short answer
Subclass TextOutputFormatter (or OutputFormatter for binary formats), override CanWriteType to declare which types it supports, set SupportedMediaTypes to the custom MIME type (like text/csv), and override WriteResponseBodyAsync to implement the actual serialization logic --…
Advertisement
AModel answer
Subclass TextOutputFormatter (or OutputFormatter for binary formats), override CanWriteType to declare which types it supports, set SupportedMediaTypes to the custom MIME type (like text/csv), and override WriteResponseBodyAsync to implement the actual serialization logic -- registered via options.OutputFormatters.Add(new CsvOutputFormatter()) in AddControllers, letting clients request text/csv via Accept to receive CSV instead of JSON from the same endpoint.
public class CsvOutputFormatter : TextOutputFormatter {
public CsvOutputFormatter() {
SupportedMediaTypes.Add("text/csv");
SupportedEncodings.Add(Encoding.UTF8);
}
protected override bool CanWriteType(Type type) => typeof(IEnumerable<Product>).IsAssignableFrom(type);
public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding encoding) {
var products = (IEnumerable<Product>)context.Object;
var csv = string.Join("\n", products.Select(p => $"{p.Id},{p.Name},{p.Price}"));
await context.HttpContext.Response.WriteAsync(csv, encoding);
}
}Real-world example
A reporting API lets analysts request the exact same /api/sales-report endpoint with Accept: text/csv to download data directly importable into Excel, without needing a separate dedicated CSV export endpoint.
Likely follow-ups
- How does a custom formatter interact with Swagger documentation generation for the extra format?
- What's the difference between TextOutputFormatter and the lower-level OutputFormatter base class?
Related topics