{"record":{"id":"f41a0261ddc06cad","repo":"dotnet/AspNetCore.Docs","slug":"httpcontext-not-available","errorCode":null,"errorMessage":"HttpContext not available","messagePattern":"HttpContext not available","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"aspnetcore/blazor/forms/validation.md","lineNumber":874,"sourceCode":"    IHttpContextAccessor httpContextAccessor, IHttpClientFactory httpClientFactory) \n    : IFormValidation\n{\n    public async Task<IDictionary<string, string[]>> ValidateStarshipFormAsync(\n        StarshipModel starship)\n    {\n        Dictionary<string, string[]> genericError = new()\n        {\n            {\n                \"Validation Error\",\n                [\"An unexpected server error occurred during validation.\"]\n            }\n        };\n\n        try\n        {\n            if (httpContextAccessor.HttpContext is null)\n            {\n                throw new Exception(\"HttpContext not available\");\n            }\n\n            var request = new HttpRequestMessage(HttpMethod.Post, \n                \"https://localhost:7277/api-starship-validation\")\n            {\n                Content = new StringContent(JsonSerializer.Serialize(starship), \n                    System.Text.Encoding.UTF8, \"application/json\")\n            };\n\n            var accessToken = \n                await httpContextAccessor.HttpContext.GetTokenAsync(\"access_token\");\n\n            request.Headers.Authorization =\n                new AuthenticationHeaderValue(\"Bearer\", accessToken);\n\n            using var httpClient = httpClientFactory.CreateClient();\n\n            var response = await httpClient.SendAsync(request);","sourceCodeStart":856,"sourceCodeEnd":892,"githubUrl":"https://github.com/dotnet/AspNetCore.Docs/blob/c67a80103a1a74db20784debd919c7fdda96c510/aspnetcore/blazor/forms/validation.md#L856-L892","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["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.","Use Blazor's recommended auth flow (AuthenticationStateProvider / IAccessTokenProvider) instead of HttpContext on the circuit.","For server-side calls, forward the token from the incoming request via a scoped provider initialized in the middleware.","Guard the access and surface a meaningful message: HttpContext is not available on an established Blazor circuit."],"exampleFix":"// before\nvar token = await httpContextAccessor.HttpContext.GetTokenAsync(\"access_token\");\n\n// after\nif (httpContextAccessor.HttpContext is null)\n    throw new InvalidOperationException(\"HttpContext is not available on an active Blazor circuit; capture the token during the initial request.\");\nvar token = await httpContextAccessor.HttpContext.GetTokenAsync(\"access_token\");","handlingStrategy":"validation","validationCode":"public string? GetAccessToken()\n{\n    var ctx = httpContextAccessor.HttpContext;\n    if (ctx is null) return null; // not available on the circuit\n    return ctx.GetTokenAsync(\"access_token\").GetAwaiter().GetResult();\n}","typeGuard":"static bool HttpContextAvailable(IHttpContextAccessor a) => a.HttpContext is not null;","tryCatchPattern":"try\n{\n    _ = httpContextAccessor.HttpContext ?? throw new InvalidOperationException(\"HttpContext not available on the circuit\");\n}\ncatch (Exception ex) when (ex.Message.Contains(\"HttpContext not available\"))\n{\n    logger.LogWarning(\"Use IAccessTokenProvider on Blazor circuits instead of HttpContext\");\n}","preventionTips":["Capture tokens/data during the initial request, not on the live circuit.","Use AuthenticationStateProvider / IAccessTokenProvider in Blazor.","Do not inject IHttpContextAccessor into long-lived component state."],"tags":["blazor","httpcontext","auth","server","configuration"],"backgroundTag":null,"analyzedSha":"c67a80103a1a74db20784debd919c7fdda96c510","analyzedAt":"2026-08-13T17:46:11.763Z","schemaVersion":2},"datasetVersion":"2026-08-13T19:17:28.613Z"}