Skip to content

Api proposal for UseStatusCodePagesWithReExecute #62408

Open
@ilonatommy

Description

@ilonatommy

Background and Motivation

The StatusCodePages middleware in ASP.NET Core provides a way to handle responses with non-success status codes. Currently, the middleware allows re-executing the pipeline for a given path, but it does not provide a way to control whether a new DI scope is created for the re-executed request. This can be important for scenarios where error handling requires a fresh scope, such as when using scoped services that should not be shared between the original and re-executed requests.

This proposal introduces a new property, CreateScopeForErrors, on StatusCodePagesOptions, and a new overload of UseStatusCodePagesWithReExecute that allows configuring this behavior.

Proposed API

namespace Microsoft.AspNetCore.Builder
{
    public class StatusCodePagesOptions
    {
+       public bool CreateScopeForErrors { get; set; }
    }

    public static class StatusCodePagesExtensions
    {
+       public static IApplicationBuilder UseStatusCodePagesWithReExecute(
+           this IApplicationBuilder app,
+           string pathFormat,
+           bool createScopeForErrors,
+           string? queryFormat = null);
    }
}

Usage Examples

app.UseStatusCodePagesWithReExecute(
    "/error/{0}",
    createScopeForErrors: true,
    queryFormat: "?originalPath={1}"
);

This will re-execute the pipeline for the /error/{statusCode} path, creating a new DI scope for the error handling request.

Alternative Designs

  • The CreateScopeForErrors property could have been added only to the options, requiring users to configure it via app.UseStatusCodePages(options => { ... }). However, providing an overload on the extension method makes it easier to opt-in for the most common scenario.
  • Other frameworks often handle error re-execution differently, but this approach is consistent with ASP.NET Core's middleware and DI patterns.

Risks

  • Creating a new DI scope for error handling may have performance implications if used excessively, but it is opt-in and should be used when isolation is required. However, we already have similar opt-in param in UseExceptionHandler:

public static IApplicationBuilder UseExceptionHandler(this IApplicationBuilder app, string errorHandlingPath, bool createScopeForErrors)

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-ready-for-reviewAPI is ready for formal API review - https://github.com/dotnet/apireviewsarea-blazorIncludes: Blazor, Razor Components

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions