{"record":{"id":"923e5249c071ebfd","repo":"dotnet/AspNetCore.Docs","slug":"httpcontext-not-available-923e52","errorCode":null,"errorMessage":"HttpContext not available","messagePattern":"HttpContext not available","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"aspnetcore/blazor/security/additional-scenarios.md","lineNumber":43,"sourceCode":"If you merely want to use access tokens to make web API calls from a Blazor Web App with a [named HTTP client](xref:blazor/call-web-api#named-httpclient-with-ihttpclientfactory), see the [Use a token handler for web API calls](#use-a-token-handler-for-web-api-calls) section, which explains how to use a <xref:System.Net.Http.DelegatingHandler> implementation to attach a user's access token to outgoing requests. The following guidance in this section is for developers who need access tokens, refresh tokens, and other authentication properties server-side for other purposes.\n\n> [!NOTE]\n> For more information on <xref:System.Net.Http.DelegatingHandler> instances, see <xref:fundamentals/http-requests#outgoing-request-middleware>.\n\nTo save tokens and other authentication properties for server-side use in Blazor Web Apps, we recommend using [`IHttpContextAccessor`/`HttpContext`](xref:blazor/components/httpcontext) (<xref:Microsoft.AspNetCore.Http.IHttpContextAccessor>, <xref:Microsoft.AspNetCore.Http.HttpContext>). Reading tokens from <xref:Microsoft.AspNetCore.Http.HttpContext>, including as a [cascading parameter](xref:Microsoft.AspNetCore.Components.CascadingParameterAttribute), using <xref:Microsoft.AspNetCore.Http.IHttpContextAccessor> is supported for obtaining tokens for use during interactive server rendering if the tokens are obtained during static server-side rendering (static SSR) or prerendering. However, tokens aren't updated if the user authenticates after the circuit is established, since the <xref:Microsoft.AspNetCore.Http.HttpContext> is captured at the start of the SignalR connection. Also, the use of <xref:System.Threading.AsyncLocal%601> by <xref:Microsoft.AspNetCore.Http.IHttpContextAccessor> means that you must be careful not to lose the execution context before reading the <xref:Microsoft.AspNetCore.Http.HttpContext>. For more information, see <xref:blazor/components/httpcontext>.\n\nIn a service class, obtain access to the members of the namespace <xref:Microsoft.AspNetCore.Authentication?displayProperty=fullName> to surface the <xref:Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.GetTokenAsync%2A> method on <xref:Microsoft.AspNetCore.Http.HttpContext>. An alternative approach, which is commented out in the following example, is to call <xref:Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.AuthenticateAsync%2A> on <xref:Microsoft.AspNetCore.Http.HttpContext>. For the returned <xref:Microsoft.AspNetCore.Authentication.AuthenticateResult.Properties%2A?displayProperty=nameWithType>, call <xref:Microsoft.AspNetCore.Authentication.AuthenticationTokenExtensions.GetTokenValue%2A>.\n\n```csharp\nusing Microsoft.AspNetCore.Authentication;\n\npublic class AuthenticationProcessor(IHttpContextAccessor httpContextAccessor)\n{\n    public async Task<string?> GetAccessToken()\n    {\n        if (httpContextAccessor.HttpContext is null)\n        {\n            throw new Exception(\"HttpContext not available\");\n        }\n\n        // Approach 1: Call 'GetTokenAsync'\n        var accessToken = await httpContextAccessor.HttpContext\n            .GetTokenAsync(\"access_token\");\n\n        // Approach 2: Authenticate the user and call 'GetTokenValue'\n        /*\n        var authResult = await httpContextAccessor.HttpContext.AuthenticateAsync();\n        var accessToken = authResult?.Properties?.GetTokenValue(\"access_token\");\n        */\n\n        return accessToken;\n    }\n}\n```\n\nThe service is registered in the server project's `Program` file:","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/dotnet/AspNetCore.Docs/blob/c67a80103a1a74db20784debd919c7fdda96c510/aspnetcore/blazor/security/additional-scenarios.md#L25-L61","documentation":"Exception(\"HttpContext not available\") thrown by AuthenticationProcessor.GetAccessToken when IHttpContextAccessor.HttpContext is null. The processor needs the current HTTP context to call GetTokenAsync(\"access_token\"). On SignalR/Blazor Server long-lived connections there is no ambient HttpContext during hub/component execution, so the accessor returns null and the guard rejects the call.","triggerScenarios":"Invoking GetAccessToken from a Blazor Server circuit after the initial HTTP request has ended; calling from a hosted service, background task, or hub method where no HTTP request is in flight; invoking outside the request pipeline.","commonSituations":"Calling token-retrieval logic from a Blazor interactive component lifecycle method that runs outside the HTTP request scope; background services that try to reuse an IHttpContextAccessor; long-running SignalR hubs.","solutions":["Capture the access token during OnInitializedAsync of the initial HTTP request (or via AuthenticationStateProvider) and pass it through, rather than reading HttpContext later.","For Blazor Server, use AuthenticationStateProvider and the persistent-component state to access tokens instead of IHttpContextAccessor.","Throw a clearer exception guiding the caller to capture the token earlier.","Restrict GetAccessToken to code paths guaranteed to run inside an HTTP request."],"exampleFix":"// before\nif (httpContextAccessor.HttpContext is null)\n{\n    throw new Exception(\"HttpContext not available\");\n}\nvar accessToken = await httpContextAccessor.HttpContext.GetTokenAsync(\"access_token\");\n\n// after — capture during the initial request and store for the circuit\nprotected override async Task OnInitializedAsync()\n{\n    var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();\n    accessToken = authState.User.FindFirst(\"access_token\")?.Value;\n}","handlingStrategy":"validation","validationCode":"if (httpContextAccessor.HttpContext is null) {\n    // capture token earlier or use AuthenticationStateProvider instead\n    return null;\n}","typeGuard":"static bool HasHttpContext(IHttpContextAccessor a) => a.HttpContext is not null;","tryCatchPattern":"try { return await processor.GetAccessToken(); }\ncatch (Exception ex) when (ex.Message.Contains(\"HttpContext not available\"))\n{\n    logger.LogWarning(ex, \"No HttpContext; capture token during the initial request.\");\n    return null;\n}","preventionTips":["Capture access tokens during the initial HTTP request and persist for the circuit.","Prefer AuthenticationStateProvider in Blazor Server over IHttpContextAccessor.","Do not call token-retrieval logic from background services or hubs.","Document which code paths are guaranteed to have an HTTP context."],"tags":["blazor","httpcontext","authentication","tokens","ihttpcontextaccessor","blazor-server"],"backgroundTag":null,"analyzedSha":"c67a80103a1a74db20784debd919c7fdda96c510","analyzedAt":"2026-08-13T17:46:11.763Z","schemaVersion":2},"datasetVersion":"2026-08-13T19:17:28.613Z"}