skip to content

In an ASP.NET Core 10 API, what is HttpContext.RequestAborted, how does a handler get it, and when should work ignore it?

level: middleimportance: should knowfreq 48%

answer

  1. a CancellationToken per request
  2. IHttpRequestLifetimeFeature behind it
  3. CancellationToken parameter binds to it
  4. HttpContext.Abort() also trips it
  5. 499 logged at Debug by the exception handler

basics

~20 s

RequestAborted is a CancellationToken that fires when the connection behind the request is aborted, by a client disconnect or HttpContext.Abort(). Handlers receive it as a CancellationToken parameter and pass it to I/O; work that must complete should not use it.

solid answer

~40 s

`HttpContext.RequestAborted` comes from `IHttpRequestLifetimeFeature`: the server cancels it when it notices the connection or HTTP/2 stream was reset, and code can trip it with `HttpContext.Abort()`. A Minimal API handler or controller action that declares a `CancellationToken` parameter gets this token without any attribute; pass it to EF Core queries, `HttpClient` calls and stream copies so the server stops wasting work on a response nobody will read. If an `OperationCanceledException` then escapes while the token is cancelled, `UseExceptionHandler` logs it at Debug and sets status 499 instead of treating it as a server error. Do not pass it to work that must finish once started, such as recording that an invoice was charged, and never use it for work that continues after the response.

code

csharp · 12 lines
csharp
app.MapPost("/invoices/{id:int}/pay", async (int id, InvoicesDb db,
    PaymentGateway gateway, CancellationToken ct) =>
{
    var invoice = await db.Invoices.FindAsync([id], ct);   // safe to cancel
    if (invoice is null) return Results.NotFound();

    var receipt = await gateway.ChargeAsync(invoice, ct);  // cancel before charge

    invoice.MarkPaid(receipt);
    await db.SaveChangesAsync(CancellationToken.None);     // must not be lost
    return Results.Ok(receipt);
});

go deeper

for a junior

Know that a handler can declare a CancellationToken parameter and should pass it to database and HTTP calls.

for a middle

Explain where the token comes from, what cancels it, how 499 and Debug logging treat a disconnect, and how request timeouts replace it.

for a senior

Decide per step which work honours the token and which must finish, especially side effects after an external charge, and keep it out of queued work.

for a principal

Set a platform convention for cancellation versus completion guarantees so services agree on which operations may be abandoned when callers disappear.

## What the token represents `HttpContext.RequestAborted` is a `CancellationToken` scoped to one request. It is a facade over `IHttpRequestLifetimeFeature`, which has two members: the `RequestAborted` token and an `Abort()` method. In Kestrel the token is backed by a `CancellationTokenSource` created the first time someone reads it, and it is cancelled when: - the server notices the client closed or reset the connection (or, on HTTP/2 and HTTP/3, reset the stream); - application code calls `HttpContext.Abort()`, which tears the connection down; - the server aborts the request itself, for example after a protocol error. Kestrel also **stops the token from firing once the whole response has been written**, so a client closing the connection after receiving its bytes does not cancel cleanup code that runs afterwards. ## How a handler gets it You almost never read `HttpContext.RequestAborted` by hand: 1. **Minimal APIs** bind a `CancellationToken` parameter to `RequestAborted` automatically. 2. **Controllers and Razor Pages** do the same through MVC's cancellation-token binder. 3. **Middleware** reads `context.RequestAborted` directly. ```csharp app.MapGet("/invoices/{id:int}/pdf", async (int id, InvoicesDb db, PdfRenderer pdf, CancellationToken ct) => { var invoice = await db.Invoices.FindAsync([id], ct); if (invoice is null) return Results.NotFound(); var bytes = await pdf.RenderAsync(invoice, ct); // stops if the client left return Results.File(bytes, "application/pdf"); }); ``` If the user closes the tab while the PDF renders, `ct` is cancelled, EF Core and the renderer throw `OperationCanceledException`, and the server stops spending CPU and database time on an answer nobody will read. ## Checking the token in your own loops Libraries that accept a `CancellationToken` check it for you. In your own long-running code you check it yourself: - call `ct.ThrowIfCancellationRequested()` between batches, for example between pages of invoice lines being aggregated; - or test `ct.IsCancellationRequested` and stop early when partial output is acceptable, such as a streamed export; - register a callback with `ct.Register(...)` only for cleanup that must react immediately, and dispose the registration. ## What happens to the exception An `OperationCanceledException` (or `IOException`) that escapes while `RequestAborted` is cancelled is treated as a **client disconnect**, not a server fault: | Pipeline piece | Behaviour when the request was aborted | |---|---| | `UseExceptionHandler` | logs "The request was aborted by the client." at **Debug**, sets **499** if the response has not started, does not run your handler | | `UseDeveloperExceptionPage` | same Debug log and 499, no error page | | No exception middleware | Kestrel itself logs "The request was aborted by the client." at Debug instead of an application error | The 499 status is never seen by the client (it is gone); it exists so logs and metrics can tell disconnects apart from 500s. ## When work should ignore it Cancelling on disconnect is right for **reads and idempotent rendering**. It is wrong for work whose partial completion is worse than finishing: - **Side effects that must be recorded.** In an invoicing API, once the payment provider has charged the card, saving the "paid" status must not be cancelled because the browser went away; pass `CancellationToken.None` or a token tied to a timeout you own for that step. - **Work that outlives the response.** Anything queued for later (sending the invoice e-mail, generating a ledger export) must not take `RequestAborted`; the token either fires early because the client disconnected or never fires because the response completed, and the context it belongs to is recycled. - **Shutdown is a different signal.** `IHostApplicationLifetime.ApplicationStopping` fires when the host stops; `RequestAborted` knows nothing about shutdown. ## RequestAborted and request timeouts The request-timeouts middleware (`AddRequestTimeouts` + `UseRequestTimeouts`) does not add a second token. For an endpoint with a timeout policy it **replaces** `HttpContext.RequestAborted` with a linked token that fires on either a disconnect or the timeout, publishes `IHttpRequestTimeoutFeature`, and restores the original token afterwards. Code that already honours `RequestAborted` therefore honours timeouts for free.

  • In ASP.NET Core 10, how does UseRequestTimeouts interact with HttpContext.RequestAborted?
    For an endpoint with a timeout policy the middleware swaps `RequestAborted` for a linked token that fires on disconnect or timeout, sets `IHttpRequestTimeoutFeature`, and restores the original token afterwards. If the timeout caused the cancellation and the response has not started, it writes the policy's status, 504 by default.
  • Why does Kestrel stop RequestAborted from firing once the response has been fully written?
    After the last byte is sent the client may close the connection normally. Cancelling then would make `OnCompleted` callbacks and cleanup look like failures, so Kestrel marks the request as done and the token stays uncancelled.

RequestAborted is like a restaurant order ticket that gets torn up when the guest walks out: the kitchen stops cooking that dish, but a payment already taken at the till is still written into the books.

  • RequestAborted fires when the app is shutting down
  • A Minimal API needs [FromServices] to receive the request CancellationToken
  • Every write after a payment should also be cancelled when the client disconnects
  • Passing RequestAborted to a fire-and-forget task makes it stop safely later
  • A disconnect shows up as a 500 error in the exception handler's logs