HttpContext is null in production but working currently in development Blazor Web App .Net 8

Prathamesh Shende 511 Reputation points
2025-07-25T13:05:08.4333333+00:00

hello,
HttpContext after successful login, it is null in production but working currently in development Blazor Web App .Net 8 Interactive Auto.

I have added this authorizationhandler and assigned to httpClient in program.cs

public class AuthorizationHandler(IHttpContextAccessor httpContextAccessor) : DelegatingHandler

{

private readonly IHttpContextAccessor _httpContextAccessor = httpContextAccessor ?? throw new ArgumentNullException(nameof(httpContextAccessor));

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)

{

    var httpContext = _httpContextAccessor.HttpContext ??

        throw new InvalidOperationException("No HttpContext available from the IHttpContextAccessor!");

    if (httpContext != null && httpContext.Request.Cookies.TryGetValue("access_token", out var token))

    {

        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

    }

    return await base.SendAsync(request, cancellationToken);

} }
```program.cs

```ruby
services.AddTransient<AuthorizationHandler>();

 var httpClientBuilder = services.AddHttpClient("ApiClient", client =>

 { client.BaseAddress = new Uri("https://localhost:7067/"); }).AddHttpMessageHandler<AuthorizationHandler>();   
```why does this not working in production?

Developer technologies | .NET | Blazor
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 79,101 Reputation points Volunteer Moderator
    2025-07-25T15:41:12.8533333+00:00

    with Interactive Auto, HttpContext is only available during pre-render. HttpContext is never available in ClientMode, and in server mode, it should only be used with static components. see thread:

    https://github.com/dotnet/AspNetCore.Docs/issues/34301

    as you want the token in client mode, on pre-render your code should write out the token to persisted state during pre-render:

    https://learn.microsoft.com/en-us/aspnet/core/blazor/components/prerender?view=aspnetcore-9.0

    The best practice would be to create a custom authentication state provider that did this:

    https://learn.microsoft.com/en-us/aspnet/core/blazor/security/authentication-state?view=aspnetcore-9.0&pivots=server


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.