dotnet/AspNetCore.Docs · error · Exception
HttpContext not available
Error message
HttpContext not available
What it means
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.
Source
Thrown at aspnetcore/blazor/security/additional-scenarios.md:43
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.
> [!NOTE]
> For more information on <xref:System.Net.Http.DelegatingHandler> instances, see <xref:fundamentals/http-requests#outgoing-request-middleware>.
To 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>.
In 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>.
```csharp
using Microsoft.AspNetCore.Authentication;
public class AuthenticationProcessor(IHttpContextAccessor httpContextAccessor)
{
public async Task<string?> GetAccessToken()
{
if (httpContextAccessor.HttpContext is null)
{
throw new Exception("HttpContext not available");
}
// Approach 1: Call 'GetTokenAsync'
var accessToken = await httpContextAccessor.HttpContext
.GetTokenAsync("access_token");
// Approach 2: Authenticate the user and call 'GetTokenValue'
/*
var authResult = await httpContextAccessor.HttpContext.AuthenticateAsync();
var accessToken = authResult?.Properties?.GetTokenValue("access_token");
*/
return accessToken;
}
}
```
The service is registered in the server project's `Program` file:View on GitHub (pinned to c67a80103a)
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.
Example fix
// before
if (httpContextAccessor.HttpContext is null)
{
throw new Exception("HttpContext not available");
}
var accessToken = await httpContextAccessor.HttpContext.GetTokenAsync("access_token");
// after — capture during the initial request and store for the circuit
protected override async Task OnInitializedAsync()
{
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
accessToken = authState.User.FindFirst("access_token")?.Value;
} Defensive patterns
Strategy: validation
Validate before calling
if (httpContextAccessor.HttpContext is null) {
// capture token earlier or use AuthenticationStateProvider instead
return null;
} Type guard
static bool HasHttpContext(IHttpContextAccessor a) => a.HttpContext is not null;
Try / catch
try { return await processor.GetAccessToken(); }
catch (Exception ex) when (ex.Message.Contains("HttpContext not available"))
{
logger.LogWarning(ex, "No HttpContext; capture token during the initial request.");
return null;
} Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- No access token
- HttpContext not available
- QR code size must be less than {MaxQrSize}.
- worker exports not loaded
- Unknown command: ${e.data.command}
AI-assisted analysis of dotnet/AspNetCore.Docs@c67a80103a (2026-08-13).
Data as JSON: /api/errors/923e5249c071ebfd.
Report an issue: GitHub.