liveBook · Manning

UseStatusCodePages

As explained in ASP.NET Core in Action, 3e

UseStatusCodePages is an ASP.NET Core application-builder extension method that adds StatusCodePagesMiddleware to the request pipeline.

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

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains registration, Problem Details integration, plain-text defaults, pipeline reexecution, redirects, and error-handler failure risks.
Examples
Demonstrates a bodyless Results.NotFound response, Problem Details output, and reexecution to a /404 endpoint.
What it assumes
Requires familiarity with ASP.NET Core middleware and AddProblemDetails when generating Problem Details responses.
What you can do after
Operate/configure status-code handling with UseStatusCodePages, Problem Details, reexecution, or redirects.
How it connects
Connects status-code handling with Problem Details, IProblemDetailsService, ExceptionHandlerMiddleware, and Razor Pages.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.