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

How would you configure an API to return Problem Details (RFC 7807) formatted error responses consistently across all content types, not just JSON?

Short answer

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…

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