Επεξεργασία

Κοινή χρήση μέσω


IHttpContextAccessor/HttpContext in ASP.NET Core Blazor apps

Note

This isn't the latest version of this article. For the current release, see the .NET 9 version of this article.

Important

This information relates to a pre-release product that may be substantially modified before it's commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.

For the current release, see the .NET 9 version of this article.

IHttpContextAccessor generally should be avoided with interactive rendering because a valid HttpContext isn't always available.

IHttpContextAccessor can be used for components that are statically rendered on the server. However, we recommend avoiding it if possible.

HttpContext can be used as a cascading parameter only in statically-rendered root components for general tasks, such as inspecting and modifying headers or other properties in the App component (Components/App.razor). The value is always null for interactive rendering.

[CascadingParameter]
public HttpContext? HttpContext { get; set; }

During interactive rendering, an HttpContext instance might not even exist. For scenarios where the HttpContext is required in interactive components, we recommend flowing context data with persistent component state from the server.

For additional context in advanced edge cases†, see the discussion in the following articles:

†Most developers building and maintaining Blazor apps don't need to delve into advanced concepts as long as the general guidance in this article is followed.

Don't use IHttpContextAccessor/HttpContext directly or indirectly in the Razor components of server-side Blazor apps. Blazor apps run outside of the ASP.NET Core pipeline context. The HttpContext isn't guaranteed to be available within the IHttpContextAccessor, and HttpContext isn't guaranteed to hold the context that started the Blazor app.

The recommended approach for passing request state to the Blazor app is through root component parameters during the app's initial rendering. Alternatively, the app can copy the data into a scoped service in the root component's initialization lifecycle event for use across the app. For more information, see ASP.NET Core server-side and Blazor Web App additional security scenarios.

A critical aspect of server-side Blazor security is that the user attached to a given circuit might become updated at some point after the Blazor circuit is established but the IHttpContextAccessor isn't updated. For more information on addressing this situation with custom services, see ASP.NET Core server-side and Blazor Web App additional security scenarios.

For guidance on IHttpContextAccessor and HttpContext in ASP.NET Core SignalR, see IHttpContextAccessor/HttpContext in ASP.NET Core SignalR.