Edit

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 11 version of this article.

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

IHttpContextAccessor can be used during static server-side rendering (static SSR), for example in statically-rendered root components, and when using a token handler for web API calls on the server. We recommend avoiding IHttpContextAccessor when static SSR or code running on the server can't be guaranteed.

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

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

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 when the general guidance in this article is followed. The most important concept to keep in mind is that HttpContext is fundamentally a server-based, request-response feature that's only generally available on the server during static SSR and only created when a user's circuit is established.

Don't set or modify headers after the response starts

Attempting to set or modify a header after the first rendering (after the response starts) results in an error:

System.InvalidOperationException: 'Headers are read-only, response has already started.'

Examples of situations that result in this error include:

For guidance on setting headers before the response starts, see ASP.NET Core Blazor startup.

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