Access HttpContext in a Blazor Razor Component
Oct 18, 2023 /
# Blazor
Before .NET 8, accessing the HttpContext in a Razor Component wasn’t possible. But that all changes in .NET 8.
Accessing HttpContext in .NET 8 Razor Components
HttpContext
can now be accessed via a [CascadingParameter]
in Razor Components.
@code {
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
}
@if (HttpContext.User.Identity.IsAuthenticated)
{
<h2>Logged in user: @HttpContext.User.Identity.Name</h2>
}
This is handy if you need to access:
- User authentication info
- Session variables
- Headers
The catch:
The component must be statically rendered (SSR mode).
This will not work if your components render mode is WASM or Server (Websockets).