dotnet/AspNetCore.Docs · error · Exception

HttpContext not available

Error message

HttpContext not available

What it means

The Blazor server-validation sample throws `Exception("HttpContext not available")` when `httpContextAccessor.HttpContext` is null. IHttpContextAccessor returns null outside an active HTTP request pipeline, so Blazor code running outside a request (e.g. on a background thread or after the circuit handshake) cannot rely on it.

Source

Thrown at aspnetcore/blazor/forms/validation.md:874

    IHttpContextAccessor httpContextAccessor, IHttpClientFactory httpClientFactory) 
    : IFormValidation
{
    public async Task<IDictionary<string, string[]>> ValidateStarshipFormAsync(
        StarshipModel starship)
    {
        Dictionary<string, string[]> genericError = new()
        {
            {
                "Validation Error",
                ["An unexpected server error occurred during validation."]
            }
        };

        try
        {
            if (httpContextAccessor.HttpContext is null)
            {
                throw new Exception("HttpContext not available");
            }

            var request = new HttpRequestMessage(HttpMethod.Post, 
                "https://localhost:7277/api-starship-validation")
            {
                Content = new StringContent(JsonSerializer.Serialize(starship), 
                    System.Text.Encoding.UTF8, "application/json")
            };

            var accessToken = 
                await httpContextAccessor.HttpContext.GetTokenAsync("access_token");

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

            using var httpClient = httpClientFactory.CreateClient();

            var response = await httpClient.SendAsync(request);

View on GitHub (pinned to c67a80103a)

Solutions

  1. Capture the access token (or needed data) during the initial HTTP request / prerender and pass it into the component or a scoped service rather than reaching for HttpContext later.
  2. Use Blazor's recommended auth flow (AuthenticationStateProvider / IAccessTokenProvider) instead of HttpContext on the circuit.
  3. For server-side calls, forward the token from the incoming request via a scoped provider initialized in the middleware.
  4. Guard the access and surface a meaningful message: HttpContext is not available on an established Blazor circuit.

Example fix

// before
var token = await httpContextAccessor.HttpContext.GetTokenAsync("access_token");

// after
if (httpContextAccessor.HttpContext is null)
    throw new InvalidOperationException("HttpContext is not available on an active Blazor circuit; capture the token during the initial request.");
var token = await httpContextAccessor.HttpContext.GetTokenAsync("access_token");
Defensive patterns

Strategy: validation

Validate before calling

public string? GetAccessToken()
{
    var ctx = httpContextAccessor.HttpContext;
    if (ctx is null) return null; // not available on the circuit
    return ctx.GetTokenAsync("access_token").GetAwaiter().GetResult();
}

Type guard

static bool HttpContextAvailable(IHttpContextAccessor a) => a.HttpContext is not null;

Try / catch

try
{
    _ = httpContextAccessor.HttpContext ?? throw new InvalidOperationException("HttpContext not available on the circuit");
}
catch (Exception ex) when (ex.Message.Contains("HttpContext not available"))
{
    logger.LogWarning("Use IAccessTokenProvider on Blazor circuits instead of HttpContext");
}

Prevention

When it happens

Trigger: Calling `httpContextAccessor.HttpContext.GetTokenAsync(...)` (or accessing HttpContext) from a context where no request is in flight — typically a Blazor Server circuit's long-lived scope or a SignalR hub invocation outside the HTTP middleware flow.

Common situations: Blazor Server component injected with IHttpContextAccessor and accessed during interactive render (HttpContext is null on the circuit); background service/HostedService reading tokens; code that works during initial prerender but fails after the WebSocket circuit takes over.

Related errors


AI-assisted analysis of dotnet/AspNetCore.Docs@c67a80103a (2026-08-13). Data as JSON: /api/errors/f41a0261ddc06cad. Report an issue: GitHub.