An ASP.NET Core 10 invoicing API reads the tenant from HttpContext inside a Task.Run started by a handler; why does it intermittently throw or read the wrong tenant?
answer
- valid until the pipeline Task completes
- DefaultHttpContext recycled per connection
- ObjectDisposedException after Uninitialize
- accessor holder nulled at request end
- copy values, then queue
basics
~20 sHttpContext lives only until the request's pipeline Task completes; then it is cleared and Kestrel reuses the same object for the next request on that connection. Late reads throw ObjectDisposedException, return null through the accessor, or see another request's tenant.
solid answer
~50 sWhen the handler returns, the request ends while the `Task.Run` keeps going. The hosting layer then clears `IHttpContextAccessor` (its shared holder is nulled, so the background task's copied `AsyncLocal` sees `null`), uninitialises the `DefaultHttpContext` (its features are dropped, so reading them throws `ObjectDisposedException`), and disposes the request's DI scope (so a captured `DbContext` throws too). Kestrel keeps that `DefaultHttpContext` with the connection and initialises it for the next request, so a closure holding the object directly can read a **different** tenant. Even before the request ends, `HttpContext` is not thread-safe, so a parallel task touching it races the handler. The fix is to copy the tenant id, user id and correlation id into plain values before starting the work, hand them to a queue processed by a hosted service with its own scope, and never pass `RequestAborted` or the context along.
code
csharp · 10 linespublic sealed record SendInvoice(string Tenant, int InvoiceId,
string? UserId, string TraceId);
// Wrong: the closure keeps the recycled HttpContext
_ = Task.Run(() => mailer.SendInvoiceAsync((string)http.Items["tenant"]!, id));
// Right: copy plain values during the request, then hand them off
var job = new SendInvoice((string)http.Items["tenant"]!, id,
http.User.FindFirst(ClaimTypes.NameIdentifier)?.Value, http.TraceIdentifier);
await queue.Writer.WriteAsync(job, http.RequestAborted);go deeper
Remember that HttpContext belongs to one running request and must not be used after the handler returns.
Explain what the hosting layer does when a request ends: accessor cleared, features dropped, scope disposed.
Diagnose intermittent ObjectDisposedException, null accessor reads and cross-tenant data back to captured contexts and context reuse, and move the work to a queue with copied values.
Make off-request work an explicit architectural path with immutable job messages, so request context cannot leak into background processing by accident.
## The symptom A SaaS invoicing API sends the invoice e-mail in the background so the endpoint can return `202 Accepted` quickly: ```csharp app.MapPost("/invoices/{id:int}/send", (int id, HttpContext http, Mailer mailer) => { _ = Task.Run(async () => { var tenant = (string)http.Items["tenant"]!; // read later, off-request await mailer.SendInvoiceAsync(tenant, id, http.RequestAborted); }); return Results.Accepted(); }); ``` Under light load it works. In production it sometimes throws `ObjectDisposedException`, sometimes `NullReferenceException` deep inside a service that uses `IHttpContextAccessor`, and occasionally an invoice goes out under **another tenant's** branding. ## What happens when the request ends The handler returns immediately, the pipeline `Task` completes and the server finishes the response. At that moment the hosting layer cleans up, while the `Task.Run` may not even have started: 1. **The accessor is cleared.** `DefaultHttpContextFactory.Dispose` sets `IHttpContextAccessor.HttpContext = null`. `HttpContextAccessor` stores its value in a static `AsyncLocal` through a shared holder object and nulls the holder's field, so the background task, which captured the same execution context, now reads `null`. 2. **The context is uninitialised.** `DefaultHttpContext.Uninitialize()` drops the feature collection. Reading `Items`, `Features` or any member of `Request` on the captured object now throws `ObjectDisposedException` ("Request has finished and HttpContext disposed" or "IFeatureCollection has been disposed"). 3. **The request scope is disposed.** `RequestServices` and every scoped service resolved from it, such as a `DbContext`, are disposed when the response completes. 4. **The object is reused.** Kestrel keeps the `DefaultHttpContext` with the HTTP/1.1 connection (or HTTP/2 stream) and, for the next request on it, **initialises the same instance** with new features. A closure holding `http` now reads the next request's `Items`, which is how one tenant's id ends up in another tenant's e-mail. Which of these the background code hits depends purely on timing, which is why the failure is intermittent. ## Why it can break even before the request ends `HttpContext` is **not thread-safe**. A `Task.Run` that reads `Items` or headers while the handler (or the framework writing the response) touches the same object is a data race on plain dictionaries and buffers. The ASP.NET Core guidance is blunt: copy what you need before starting parallel work. ## The `RequestAborted` trap Passing `http.RequestAborted` to background work is wrong in both directions: - if the client disconnects early, the e-mail is cancelled for no business reason; - once the full response is written, Kestrel stops that token from firing, so it no longer cancels anything; it never signals shutdown. ## The fix | Do | Instead of | |---|---| | copy `tenant`, `userId`, `TraceIdentifier` into a record | capturing `HttpContext` in a closure | | enqueue the record and return `202` | `Task.Run` or `async void` from a handler | | let a hosted service create its own DI scope per item | reusing the request's `DbContext` | | use the hosted service's `stoppingToken` | `HttpContext.RequestAborted` | ```csharp app.MapPost("/invoices/{id:int}/send", async (int id, HttpContext http, Channel<SendInvoice> queue) => { var job = new SendInvoice((string)http.Items["tenant"]!, id, http.User.FindFirst(ClaimTypes.NameIdentifier)?.Value, http.TraceIdentifier); await queue.Writer.WriteAsync(job, http.RequestAborted); // only the hand-off return Results.Accepted(); }); ``` The background consumer reads `SendInvoice` items, creates a scope with `IServiceScopeFactory` for each one and never touches an `HttpContext`. Services it calls must take the tenant as an argument (or from a scoped tenant context the consumer fills), not from `IHttpContextAccessor`, which is `null` there by design. ## Why `async void` is the same bug An `async void` controller action is fire-and-forget in disguise: the framework sees a method that returned, ends the request at the first `await`, and the rest of the method runs against a recycled context. The ASP.NET Core performance guidance calls `async void` always a bad practice in request code for exactly this reason. Return `Task` (or `Task<IResult>`) so the request stays alive until the work completes, or queue the work explicitly as shown above. ## How to find the culprits - Search for `Task.Run`, `_ =` discards, `async void` and `ContinueWith` in controllers, handlers and middleware. - Look for `IHttpContextAccessor` in classes registered as singletons or used by hosted services. - Treat a `NullReferenceException` from `accessor.HttpContext` or an `ObjectDisposedException` naming `HttpContext` or `IFeatureCollection` as a pointer to off-request access.
- Why can a captured ASP.NET Core HttpContext show another request's data instead of throwing?Kestrel pools the hosting context per connection or stream. After a request ends it uninitialises the `DefaultHttpContext` and, for the next request on that connection, initialises the same instance with new features, so a stale reference reads the new request's values.
- A service used by a hosted worker throws NullReferenceException on accessor.HttpContext; what is the fix in ASP.NET Core 10?The worker has no request, so the accessor correctly returns `null`. Change the service to take the tenant or user as an argument, or read them from a scoped context object that the worker fills per item, and keep `IHttpContextAccessor` to request-time code.
- Task.Run copies HttpContext, so the background task gets its own safe snapshot
- IHttpContextAccessor keeps returning the original context inside background work
- HttpContext is thread-safe because each request has its own instance
- Passing RequestAborted to queued work stops it cleanly at shutdown
- Each request always gets a brand-new HttpContext object, so stale reads are impossible