In ASP.NET Core, how do UseStatusCodePages, UseStatusCodePagesWithRedirects and UseStatusCodePagesWithReExecute differ in what a client receives for an empty 404?
answer
- only bodiless 400-599 responses
- default: text/plain or ProblemDetails
- redirects send 302, then 200
- re-execute keeps the status and URL
- IStatusCodeReExecuteFeature.OriginalPath
basics
~20 sAll three fill responses with status 400-599 that have no body. UseStatusCodePages writes a plain-text or ProblemDetails body in place, WithRedirects sends a 302 to an error URL, and WithReExecute runs the pipeline again at an error path while keeping the original status.
solid answer
~40 sThe status code pages middleware acts only when the response has not started, its status is 400-599, and it has neither a `Content-Length` nor a `Content-Type`. `UseStatusCodePages()` writes a body in place: a ProblemDetails document when `AddProblemDetails()` registered `IProblemDetailsService`, otherwise `text/plain` like `Status Code: 404; Not Found`; overloads take a content type and format string, a handler lambda or a branch. `UseStatusCodePagesWithRedirects("/errors/{0}")` answers 302 Found, so the browser lands on the error URL with a 200 and the original 404 is lost. `UseStatusCodePagesWithReExecute("/errors/{0}")` reruns the pipeline at that path, keeps the URL and the original status unless the error page changes it, and exposes `IStatusCodeReExecuteFeature`. `[SkipStatusCodePages]` or `IStatusCodePagesFeature.Enabled = false` opts a response out.
code
csharp · 13 linesapp.UseStatusCodePagesWithReExecute("/errors/{0}");
app.Map("/errors/{code:int}", (int code, HttpContext context) =>
{
var original = context.Features.Get<IStatusCodeReExecuteFeature>();
var path = WebUtility.HtmlEncode(original?.OriginalPath ?? "this page");
var message = code == StatusCodes.Status404NotFound
? $"We could not find {path} in the catalogue."
: "Something went wrong with your request.";
// No status code set here, so the original 404 reaches the reader.
return Results.Content($"<h1>{message}</h1>", "text/html");
});go deeper
Remember that status code pages fill empty error responses and that there are three flavours: in place, redirect and re-execute.
Explain the skip conditions (started, outside 400-599, Content-Type or Content-Length set) and why re-execute keeps the status while redirects lose it.
Pick re-execute for public pages that must keep 404 for crawlers, ProblemDetails for APIs, and opt endpoints out with SkipStatusCodePages or IStatusCodePagesFeature.
Set one policy for bodiless errors across HTML and API surfaces so every service answers 4xx consistently without per-endpoint code.
## What status code pages are for Many 4xx and 5xx responses leave ASP.NET Core with **no body at all**: a URL that matches no endpoint (404), a `Results.NotFound()` or `NotFound()` without a value, an authorization failure (401 or 403), a method mismatch (405). A browser then shows its own blank error screen and an API client gets nothing to parse. The **status code pages middleware** in `Microsoft.AspNetCore.Diagnostics` fills those empty responses. It does not catch exceptions; that is `UseExceptionHandler`'s job. ## When the middleware acts It runs the rest of the pipeline first, then looks at the response. It does nothing if any of these is true: - the response has already started (`Response.HasStarted`); - the status is below 400 or 600 and above; - the response has a `Content-Length` or a `Content-Type`, meaning something already wrote or declared a body; - the endpoint carries `ISkipStatusCodePagesMetadata` (the MVC and Razor Pages `[SkipStatusCodePages]` attribute implements it); - code set `IStatusCodePagesFeature.Enabled = false` for this request. So a 404 that already carries a ProblemDetails JSON body is left alone. ## The three flavours | Call | What the client receives for an empty 404 | Status the client sees | URL in the address bar | |---|---|---|---| | `UseStatusCodePages()` | a body written in place | 404 | unchanged | | `UseStatusCodePagesWithRedirects("/errors/{0}")` | a redirect, then the error page | 302, then usually 200 | changes to `/errors/404` | | `UseStatusCodePagesWithReExecute("/errors/{0}")` | the error page's output | 404, unless the page sets another | unchanged | **`UseStatusCodePages()`**: the default handler asks `IProblemDetailsService` for a ProblemDetails body when one is registered; otherwise it writes `text/plain` such as `Status Code: 404; Not Found`. Other overloads take `(contentType, bodyFormat)` with `{0}` standing for the code, a `Func<StatusCodeContext, Task>`, or an `Action<IApplicationBuilder>` branch. A custom `Func<StatusCodeContext, Task>` receives a `StatusCodeContext` with three members: `HttpContext` (read `Response.StatusCode` there), `Options` (the `StatusCodePagesOptions` in use) and `Next` (the rest of the pipeline, which the re-execute flavour calls). Whatever the lambda writes becomes the body; it should set `Response.ContentType` itself. **`UseStatusCodePagesWithRedirects(locationFormat)`**: calls `Response.Redirect`, which sends **302 Found**. The browser then requests the error page and gets whatever it returns, usually 200. Crawlers and clients lose the real status, and the redirect costs a round trip. A location starting with `~` gets `PathBase` prepended. **`UseStatusCodePagesWithReExecute(pathFormat, queryFormat, createScopeForStatusCodePages)`**: rewrites `Request.Path` (and optionally the query string) and runs the pipeline again on the same request. The original status stays unless the error endpoint sets another. The error page can read **`IStatusCodeReExecuteFeature`**: - `OriginalPath`, `OriginalPathBase` and `OriginalQueryString`, which the page can show ("no book at /catalogue/books/978-0"); - `OriginalStatusCode`; - `Endpoint` and `RouteValues` of the original request. ## Choosing one for a public catalogue A public library catalogue wants a friendly "book not found" page that keeps the 404, so search engines drop dead links and the address bar still shows what the reader typed. That is re-execute: 1. Map an error endpoint that accepts any method, for example `app.Map("/errors/{code:int}", ...)`. 2. Read `IStatusCodeReExecuteFeature` to show the original path. 3. Return HTML without setting a status, so the 404 survives. The .NET 10 Blazor Web App template uses the same mechanism: it calls `UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true)` and ships a not-found page. `createScopeForStatusCodePages` gives the re-execution a fresh DI scope. For a JSON API, plain `UseStatusCodePages()` plus `AddProblemDetails()` is usually enough: every empty error status gets a ProblemDetails body. ## Pitfalls - Expecting status code pages to handle exceptions: an exception is turned into a response by `UseExceptionHandler`, not by this middleware. - Choosing redirects for SEO-sensitive pages and then wondering why crawlers index the error page as a 200. - Expecting a 404 with a JSON body to be replaced: a `Content-Type` already set means the middleware leaves the response alone.
- Why does an endpoint that returns a 404 ProblemDetails body never reach the status code page?The middleware checks the response after the endpoint ran and skips it when `Content-Type` or `Content-Length` is set, when the response has started, or when the status is outside 400-599. A ProblemDetails result sets `application/problem+json`, so the response already has a body and is left as it is.
- How do you stop UseStatusCodePages from touching one endpoint's responses?Mark an MVC action or Razor Page with `[SkipStatusCodePages]`, which implements `ISkipStatusCodePagesMetadata`, or set `context.Features.Get<IStatusCodePagesFeature>()!.Enabled = false` in code for that request. Any endpoint whose metadata includes `ISkipStatusCodePagesMetadata` is skipped.
- UseStatusCodePagesWithRedirects keeps the original 404 status for browsers and crawlers.
- UseStatusCodePages rewrites every 4xx response, even ones that already carry a JSON body.
- UseStatusCodePages catches exceptions and turns them into 500 pages.
- With UseStatusCodePagesWithReExecute the browser's address bar changes to the error page URL.
Assumes ASP.NET Core 10, whose Blazor Web App template calls UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true) for its not-found page.