skip to content

An ASP.NET Core insurance-claims search action keeps querying the database after callers disconnect; how do you make the controller honour cancellation, and what happens when it fires?

level: seniorimportance: should knowfreq 45%

answer

  1. the token is a parameter, not a field
  2. CancellationTokenModelBinder reads RequestAborted
  3. pass ct to every async call
  4. OperationCanceledException bubbles up
  5. Debug log and status 499

basics

~20 s

Add a CancellationToken parameter to the action, which MVC binds to HttpContext.RequestAborted, and pass it to every async call. A disconnect then throws OperationCanceledException, which the exception middleware logs at Debug and maps to 499.

solid answer

~40 s

MVC binds any `CancellationToken` action parameter through `CancellationTokenModelBinder`, which hands you `HttpContext.RequestAborted`; it has a special binding source, so `[ApiController]` never tries to read it from the query. The token only helps if you pass it on: `ToListAsync(ct)`, `FirstOrDefaultAsync(..., ct)`, `HttpClient.GetAsync(url, ct)`. When the client goes away, the awaited call throws `OperationCanceledException` and the action unwinds. Don't catch it to return a result nobody will read. `UseExceptionHandler` and the developer exception page recognise an `OperationCanceledException` or `IOException` while `RequestAborted` is cancelled: they log "The request was aborted by the client." at Debug and set 499 if the response has not started, and Kestrel logs an aborted connection's cancellation at Debug too. For writes, decide deliberately: cancelling before `SaveChangesAsync` commits is safe, but side effects such as a payment call may need to finish.

code

csharp · 18 lines
csharp
[HttpGet("{id:int}/documents")]
public async Task<ActionResult<List<DocumentDto>>> Documents(int id, CancellationToken ct)
{
    try
    {
        var docs = await _documents.ListForClaimAsync(id, ct);
        return docs.Count == 0 ? NotFound() : docs;
    }
    catch (OperationCanceledException) when (ct.IsCancellationRequested)
    {
        throw;                      // caller is gone: let the middleware log at Debug
    }
    catch (DocumentStoreException ex)
    {
        _logger.LogError(ex, "Document store failed for claim {ClaimId}", id);
        return Problem(statusCode: StatusCodes.Status502BadGateway);
    }
}

go deeper

for a junior

Recall that an async action takes a CancellationToken parameter and passes it to every async call such as ToListAsync(ct).

for a middle

Explain how CancellationTokenModelBinder supplies RequestAborted, how OperationCanceledException unwinds, and why the token never becomes a query parameter.

for a senior

Diagnose load caused by abandoned requests, keep disconnects out of error logs, and choose per write whether cancellation is safe.

for a principal

Make cancellation a codebase rule with analyzers and review checklists, and define which side effects must complete regardless of the caller.

## The symptom A claims-search endpoint runs an expensive query: full-text match on descriptions, joins to policies and payments. Front-end users type, change their mind and navigate away, and the browser aborts the request. The server, however, keeps the database busy until each query finishes, and under load the abandoned queries starve the ones whose callers are still waiting. The cause is almost always the same: **nothing passes the request's cancellation signal to the database call.** ## Where the token comes from Every ASP.NET Core request has `HttpContext.RequestAborted`, a `CancellationToken` that the server signals when it notices the client connection has gone away (or when something aborts the request). In a controller you do not reach for `HttpContext`; you declare a parameter: ```csharp [HttpGet("search")] public async Task<ActionResult<List<ClaimSummary>>> Search( string q, int page, CancellationToken ct) { return await _db.Claims .Where(c => EF.Functions.Like(c.Description, $"%{q}%")) .OrderByDescending(c => c.FiledOn) .Skip(page * 50).Take(50) .Select(c => new ClaimSummary(c.Id, c.Status, c.FiledOn)) .ToListAsync(ct); } ``` MVC registers a `CancellationTokenModelBinderProvider`, and `CancellationTokenModelBinder` sets the parameter to `bindingContext.HttpContext.RequestAborted`. The type is also given `BindingSource.Special` and excluded from validation, so `[ApiController]`'s inference never turns it into a query parameter, and it never appears in the OpenAPI document. ## What happens when it fires 1. The client disconnects; the server cancels `RequestAborted`. 2. The awaited operation that received the token (EF Core's `ToListAsync`, an `HttpClient` call, `Task.Delay`) throws `OperationCanceledException` (often its subclass `TaskCanceledException`). EF Core asks the provider to cancel the running command. 3. The exception unwinds through the action and the MVC filters. 4. If `UseExceptionHandler` or the developer exception page is in the pipeline, it checks for `OperationCanceledException` or `IOException` while `RequestAborted.IsCancellationRequested` is true. In that case it logs "The request was aborted by the client." at **Debug** level, sets the status to `StatusCodes.Status499ClientClosedRequest` if the response has not started, and does **not** run your error handler or write an error body. 5. Kestrel makes a similar check when such an exception reaches it on a connection that was aborted, again logging at Debug instead of reporting an application error. The result: no error-level noise and no work after the caller has left, as long as the token was passed down. ## Mistakes that defeat it - **Taking the token and not passing it.** The parameter is harmless on its own; only the calls that receive it can stop. - **Catching everything.** A `catch (Exception ex)` that logs an error and returns `StatusCode(500)` turns every disconnect into an alert. Catch `OperationCanceledException` separately, or let it propagate. - **Using a different token.** A `CancellationTokenSource` you create yourself has nothing to do with the request; link it with `CancellationTokenSource.CreateLinkedTokenSource(ct)` if you also need a local timeout. Note that an `OperationCanceledException` from your own timeout is a real failure and the middleware treats it as one, because `RequestAborted` is not cancelled. - **Sync-over-async.** `.Result` or `.Wait()` on a database call ignores the token's purpose and blocks a thread-pool thread. ## Reads versus writes For reads, always pass the token: an abandoned read has no value. For writes, choose per operation: - Cancelling an EF Core `SaveChangesAsync(ct)` that has not committed yet leaves the database unchanged, because the batch is applied atomically, inside a transaction when it needs one. - A claim submission that also calls a payment provider or sends a notification should not be stopped half-way; finish that part with `CancellationToken.None` and make it idempotent, or hand it to background work. ## Where else the token belongs The same parameter should flow into everything the action awaits: repository methods (give each one a `CancellationToken` parameter instead of reaching for `IHttpContextAccessor`), outgoing `HttpClient` calls, `Task.Delay` in a polling loop, and `ReadAsync` on request or blob streams. A service method that does not take a token is a dead end; adding one later means changing every caller, so make it part of the signature from the start. Filters get the same token from `context.HttpContext.RequestAborted`. ## Testing it In a unit test, call the action with a token from a `CancellationTokenSource` you cancel, and assert that the fake store observed the token or that `OperationCanceledException` propagates. In an integration test, cancel the `HttpClient` call and check the server log for the Debug message instead of an error.

  • Does adding CancellationToken to every action add a parameter to the OpenAPI document?
    No. `CancellationToken` has `BindingSource.Special`, so ApiExplorer does not describe it as a query, route or body parameter, and `[ApiController]` inference leaves it alone. It costs nothing to declare, which is why many teams add it to every async action.
  • Why does a cancellation from your own timeout still show up as an error?
    The exception middleware treats `OperationCanceledException` as a client abort only when `HttpContext.RequestAborted.IsCancellationRequested` is true. A timeout from your own `CancellationTokenSource` leaves `RequestAborted` untouched, so it is handled as an ordinary unhandled exception, which is correct: the server gave up, the client did not.
  • Should the action catch OperationCanceledException and return a result?
    No. The client has disconnected, so any result is written to nobody. Let it propagate so the framework logs it at Debug and sets 499, or rethrow it if it passes through a broader catch.

A cancelled restaurant order only stops the stations that were handed the ticket: if the waiter tears up the order but the grill never got a copy, the steak is cooked anyway. The CancellationToken is that ticket, and every awaited call is a station that must receive it.

  • Declaring a CancellationToken parameter cancels the query even if it is not passed on.
  • ASP.NET Core aborts the action thread when the client disconnects.
  • Every OperationCanceledException means the client disconnected, even one from your own timeout.
  • The CancellationToken parameter is read from a ?ct= query string value.
  • A disconnect should be caught and answered with a 500 so it is visible in logs.