UseStatusCodePages is an ASP.NET Core application-builder extension method that adds StatusCodePagesMiddleware to the request pipeline. The middleware watches for 4xx and 5xx responses that have no body and supplies an error response. section 5.3.3 section 15.5
For JSON APIs, register AddProblemDetails() as well. StatusCodePagesMiddleware then adds a Problem Details body to eligible error responses, including errors produced by endpoints or other middleware. section 5.3.3
Add Problem Details for a 404 response
builder.Services.AddProblemDetails(); var app = builder.Build(); app.UseStatusCodePages(); app.MapGet("/", () => Results.NotFound()); app.Run(); The 404 response has no body initially, so the middleware adds a Problem Details body. section 5.3.3
Choose the status-code handling style that matches the application:
- UseStatusCodePages() for basic handling; its default response is a plain-text error body and is mainly useful as a starting point. section 15.5
- UseStatusCodePagesWithReExecute("/{0}") to rerun the pipeline, replacing {0} with the status code so /404 can render a tailored page. section 15.5
- Prefer a reliable static error page when possible, because a failing dynamic error handler can leave the user with a generic browser error. section 15.5
