ASP.NET Core's ProblemDetails support is primarily JSON-oriented by default, but for an API also supporting XML output, you'd need either a custom output formatter capable of serializing ProblemDetails objects to XML, or a deliberate architectural decision to always return error responses in JSON regardless of the requested success-response format (a common, pragmatic simplification many APIs make, treating error responses as an exception to normal content negotiation rules).
// Pragmatic approach: always return errors as JSON, regardless of negotiated success format
app.UseExceptionHandler(exceptionApp => {
exceptionApp.Run(async context => {
context.Response.ContentType = "application/problem+json"; // always JSON for errors
await context.Response.WriteAsJsonAsync(new ProblemDetails { Title = "An error occurred" });
});
});
Real-world example
An API supporting both JSON and XML for successful responses deliberately always returns errors as application/problem+json, documenting this exception clearly so XML consumers know to expect JSON specifically for the error case.
Likely follow-ups
Is it more correct to fully support ProblemDetails in every negotiated format, or is the JSON-only exception acceptable?
How would clients discover this documented inconsistency?
Global Exception Handling & MiddlewareError Handling
The Vary: Accept header tells caches (browsers, CDNs, reverse proxies) that a response's content differs based on the request's Accept header value, preventing a cache from incorrectly serving a JSON-cached response to a client that requested XML (or vice versa) -- content-negotiating endpoints should ensure Vary: Accept (and potentially Vary: Accept-Language for localized content) is set so intermediary caches respect the negotiation dimension when deciding whether a cached response is reusable.
// A caching proxy without seeing Vary: Accept might incorrectly serve
// a cached JSON response to a client that explicitly requested XML
Response.Headers.Vary = "Accept"; // tells caches: responses differ based on Accept header value
Real-world example
A CDN caching an API's responses without respecting the Vary: Accept header once served a JSON response to an XML-requesting client, a subtle caching bug traced back to the missing Vary header on a content-negotiating endpoint.
Likely follow-ups
How does Vary interact with Response Caching middleware's VaryByHeader configuration?
What other request headers commonly need to be included in Vary for correctness?
This scenario combines versioning concerns (which schema to use) with content negotiation concerns (which serialization format to use) -- typically handled by separating them: API versioning (via URL segment, header, or Asp.Versioning) determines the response schema/DTO to use, while standard content negotiation (Accept header, output formatters) independently determines the serialization format of whichever schema was selected, keeping the two orthogonal concerns cleanly separated rather than conflating them into a single mechanism.
[ApiVersion("2.0")]
[Produces("application/json", "application/xml")] // format negotiation, independent of version
[HttpGet("{id}")]
public IActionResult GetProduct(int id) {
var v2Dto = MapToV2(product); // version determines SCHEMA
return Ok(v2Dto); // content negotiation determines FORMAT (JSON or XML) of that schema
}
Real-world example
An API cleanly separates 'which version's schema to return' (handled by Asp.Versioning based on URL segment) from 'which format to serialize that schema in' (handled by standard Accept-header content negotiation), avoiding a confusing conflation of the two orthogonal concerns.
Likely follow-ups
Why is conflating versioning and format negotiation into one mechanism generally considered poor design?
How would documentation clearly communicate this two-dimensional selection to API consumers?
API VersioningAPI Documentation with Swagger/OpenAPI
406 Not Acceptable indicates the server understood the request but cannot produce a response matching any of the media types the client is willing to accept -- ASP.NET Core can be configured to return this automatically when RespectBrowserAcceptHeader-style strict negotiation is enabled and no registered formatter matches, rather than silently falling back to a default format the client didn't actually request.
Example
// Client sends: Accept: application/pdf
// No PDF formatter registered for this endpoint
// Response: 406 Not Acceptable (if strict negotiation is configured)
Real-world example
An API configured for strict content negotiation correctly returns 406 when a client mistakenly requests an unsupported Accept: application/pdf, giving clear, actionable feedback instead of silently returning JSON the client didn't ask for.
Likely follow-ups
What's the default behavior if strict negotiation isn't explicitly configured?
How does a client typically discover which formats are actually supported?
Using WebApplicationFactory, set the Accept header explicitly on the HttpClient request before calling the endpoint, then assert both the response's Content-Type header and that the body successfully deserializes as the expected format, verifying the full content negotiation behavior end-to-end rather than just testing the default JSON path.
[Fact]
public async Task GetProduct_WithXmlAccept_ReturnsXml() {
var client = _factory.CreateClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));
var response = await client.GetAsync("/api/products/1");
Assert.Equal("application/xml", response.Content.Headers.ContentType.MediaType);
}
Real-world example
A test suite explicitly verifies both JSON and XML content negotiation paths for a dual-format endpoint, catching a regression where a refactor accidentally removed the XML formatter registration, breaking legacy XML-consuming clients silently.
Likely follow-ups
How would you parameterize this test to cover multiple Accept header scenarios efficiently?
What's the risk of only ever testing the default JSON path?
Testing ASP.NET Core ApplicationsRESTful Web APIs & Controllers