How do you add XML output formatting support to an ASP.NET Core API alongside the default JSON formatter?
Short answer
AddXmlSerializerFormatters() (or AddXmlDataContractSerializerFormatters() for an alternative serialization approach) registers XML input/output formatters alongside the default JSON ones, letting the same controllers serve both formats automatically based on content negotiation…
Advertisement
AModel answer
AddXmlSerializerFormatters() (or AddXmlDataContractSerializerFormatters() for an alternative serialization approach) registers XML input/output formatters alongside the default JSON ones, letting the same controllers serve both formats automatically based on content negotiation without any per-action code changes.
builder.Services.AddControllers()
.AddXmlSerializerFormatters();
// Now both of these work automatically:
// GET /api/products/1 Accept: application/json -> JSON response
// GET /api/products/1 Accept: application/xml -> XML responseReal-world example
A B2B integration platform serving both modern partners (JSON) and legacy enterprise systems (XML) adds XML formatters once at startup, letting every existing controller serve both formats without touching individual action methods.
Likely follow-ups
- What are the performance and complexity trade-offs of supporting multiple output formats?
- How does XML serialization handle types that don't map cleanly to XML, like dictionaries?
Related topics