skip to content

In ASP.NET Core 10, how does IHttpContextAccessor find the current request, and what does injecting it into a service cost?

level: middleimportance: must knowfreq 58%

answer

  1. AddHttpContextAccessor, singleton
  2. static AsyncLocal holding a holder object
  3. set at request start, cleared at end
  4. null outside a request
  5. IActionContextAccessor obsolete: ASPDEPR006

basics

~20 s

AddHttpContextAccessor registers a singleton HttpContextAccessor that keeps the current HttpContext in a static AsyncLocal, set when the request starts and cleared when it ends. It returns null outside a request and hides a request dependency inside the service.

solid answer

~40 s

`builder.Services.AddHttpContextAccessor()` does a `TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>()`. When a request starts, the hosting layer's `DefaultHttpContextFactory` sets `accessor.HttpContext`, which stores a small holder object in a static `AsyncLocal`; the value flows with the `ExecutionContext` into every `await` continuation of that request. When the request ends it clears the holder, so any code still holding that execution context sees `null`. The costs: an `AsyncLocal` write on every request once it is registered, a service that silently returns `null` at startup, in background work or in tests, and a hidden dependency that is easy to misuse by caching `HttpContext` in a field. Read `accessor.HttpContext` at the moment you need it, never in a constructor, and prefer passing the values in. In ASP.NET Core 10 `IActionContextAccessor` is obsolete (`ASPDEPR006`); use `IHttpContextAccessor` with `HttpContext.GetEndpoint()`.

code

csharp · 10 lines
csharp
public sealed class InvoiceNumbering(IHttpContextAccessor accessor) : IInvoiceNumbering
{
    public string Next(int sequence)
    {
        var http = accessor.HttpContext
            ?? throw new InvalidOperationException("No active request.");
        var tenant = (string?)http.Items["tenant"] ?? "unknown";
        return $"{tenant}-{DateTime.UtcNow:yyyy}-{sequence:D6}";
    }
}

go deeper

for a junior

Know that a service outside the pipeline injects IHttpContextAccessor after AddHttpContextAccessor, and that HttpContext can be null there.

for a middle

Explain the singleton plus AsyncLocal mechanism, when the hosting layer sets and clears it, and why the value must be read at call time.

for a senior

Weigh the hidden dependency and null cases against passing values explicitly or a scoped tenant context, and migrate IActionContextAccessor (ASPDEPR006) to GetEndpoint().

for a principal

Decide whether request context is allowed to leak into domain services at all, and enforce one typed abstraction rather than ad hoc accessor use across teams.

## Registering it `IHttpContextAccessor` is **not** registered by `WebApplication.CreateBuilder` on its own. You opt in: ```csharp builder.Services.AddHttpContextAccessor(); builder.Services.AddScoped<IInvoiceNumbering, InvoiceNumbering>(); ``` `AddHttpContextAccessor` calls `TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>()`, so it is safe to call more than once, and some framework features (ASP.NET Core Identity's `AddIdentity`, for instance) call it for you. The service is a **singleton**: one accessor object serves every request. ## How a singleton knows the current request The trick is an `AsyncLocal`: 1. `HttpContextAccessor` holds a `static AsyncLocal<HttpContextHolder>`. The holder is a tiny class with one `HttpContext?` field. 2. When the server hands a request to the hosting layer, `DefaultHttpContextFactory` initialises the `DefaultHttpContext` and, **only if an accessor is registered**, sets `accessor.HttpContext = httpContext`. That stores a new holder in the `AsyncLocal` for the current `ExecutionContext`. 3. Every `await` continuation, and every `Task.Run` started from the request, captures the `ExecutionContext` and therefore sees the same holder. 4. When the request finishes, the factory sets `accessor.HttpContext = null`. The setter first nulls the field **inside the existing holder**, and that is why the holder exists: every copied execution context points at the same holder object, so they all see `null` from then on instead of a stale, recycled context. The getter is just `_httpContextCurrent.Value?.Context`, so outside a request (startup code, a hosted service, a timer callback, a unit test) it returns **`null`**. ## What it costs | Cost | Why it matters | |---|---| | Per-request work | once registered, every request writes and later clears the `AsyncLocal`; small, but not free | | `null` outside a request | code that works in an endpoint throws `NullReferenceException` in a background job or a test | | Hidden dependency | the constructor says "accessor", not "needs a tenant id", so callers cannot see or supply the input | | Easy misuse | storing `accessor.HttpContext` in a field captures `null` or an earlier request's context | | Thread safety | the returned `HttpContext` is still not thread-safe; parallel tasks must not share it | ## Using it well - **Read it late.** Keep the accessor in a field and read `.HttpContext` inside the method that needs it, checking for `null`. - **Pull values at the edge.** In a Minimal API handler or a controller you already have the context; pass the tenant id or `ClaimsPrincipal` as an argument instead of letting a deep service reach back for it. - **Wrap it once.** If many services need the tenant, a scoped `ITenantContext` that reads the accessor (or is filled by middleware) gives them a typed, testable input and keeps the accessor in one place. - **Never rely on it in background work.** A hosted service has no request; work queued from a request must carry copies of the values it needs. ## Testing services that use it `HttpContextAccessor` has a public setter, so a unit test can give a service a context without a server: ```csharp var accessor = new HttpContextAccessor { HttpContext = new DefaultHttpContext() }; accessor.HttpContext!.Items["tenant"] = "acme"; var numbering = new InvoiceNumbering(accessor); ``` The value flows through the test's own execution context exactly as it would in a request. The awkwardness of that setup, compared with simply passing `"acme"` to the method, is a good argument in an interview for keeping the accessor at the edges of the application. ## What changed in .NET 10 ASP.NET Core 10 marks `IActionContextAccessor` and `ActionContextAccessor` obsolete with diagnostic **`ASPDEPR006`**. With endpoint routing, the current action's metadata is on the endpoint, so the replacement is `IHttpContextAccessor` plus `HttpContext.GetEndpoint()` (for example `GetEndpoint()?.Metadata.GetMetadata<ControllerActionDescriptor>()`). Code that still injects `IActionContextAccessor` compiles with a warning on `net10.0` and should be migrated.

  • Why does HttpContextAccessor store a holder object in the AsyncLocal instead of the HttpContext itself?
    Execution contexts are copied into every continuation and `Task.Run`. Clearing an `AsyncLocal` value only affects the current context, but nulling the field inside the shared holder affects every copy, so code that outlives the request sees `null` rather than a recycled `HttpContext`.
  • In ASP.NET Core 10, how do you read the current controller action's descriptor now that IActionContextAccessor is obsolete?
    Inject `IHttpContextAccessor`, read `HttpContext.GetEndpoint()` and take `Metadata.GetMetadata<ControllerActionDescriptor>()`. Inside a controller or filter you already have the context, so you call `GetEndpoint()` on it directly.

  • IHttpContextAccessor is registered by default, so no AddHttpContextAccessor call is needed
  • The accessor is scoped, so each request gets its own instance
  • Storing accessor.HttpContext in a constructor field is fine because AsyncLocal keeps it current
  • The accessor returns the last request's context inside a hosted service
  • IActionContextAccessor is still the recommended way to reach ActionContext in .NET 10

Assumes ASP.NET Core 10; IActionContextAccessor became obsolete (ASPDEPR006) in 10, leaving IHttpContextAccessor plus GetEndpoint() as the supported route.