Advertisement
Intermediate ASP.NET Core, Content Negotiation & Output Formatters

How do you test that an API correctly returns different formats based on the Accept header using integration tests?

Short answer

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…

Save ASP.NET Core mock interview
Advertisement
AModel answer
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?
Related topics