Explain how cancellation tokens should flow from an ASP.NET Core request into database and HTTP calls.
Swiggy · Full Stack Developer · 3-4-years · technical
Published
Year not specified · .NET, C#, ASP.NET Core
Community answers
Posted by wasAsked editorial collection
ASP.NET Core exposes `HttpContext.RequestAborted`. Accept it as a `CancellationToken` action parameter and pass the same token through every cancellable layer. Cancellation is cooperative: each operation must observe the token. Do not replace it with `CancellationToken.None`, and do not convert a client disconnect into a generic server error.
```csharp
[HttpGet("{id:guid}")]
public async Task<ActionResult<OrderDto>> Get(
Guid id, CancellationToken cancellationToken)
{
var order = await repository.FindAsync(id, cancellationToken);
if (order is null) return NotFound();
using var request = new HttpRequestMessage(
HttpMethod.Get, $"risk/{order.CustomerId}");
using var response = await httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
return Ok(Map(order));
}
```
For an application timeout, link it with the request token using `CancellationTokenSource.CreateLinkedTokenSource`, then call `CancelAfter`. Catch `OperationCanceledException` only when you can add meaning or distinguish timeout from caller cancellation; otherwise let the framework complete cancellation handling. Never reuse a disposed token source.
Krishna Yadav · · 0 likes
A cancellation token tells downstream work to stop when it is no longer needed — for example when the user closes the page or a timeout expires. In ASP.NET Core it should flow from the request through every async call.
1. Get the token at the edge
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id, CancellationToken ct) // bound to HttpContext.RequestAborted
{
var report = await _service.BuildAsync(id, ct);
return Ok(report);
}
Minimal APIs bind a CancellationToken parameter the same way.
2. Pass it through every layer
- Service and repository methods accept CancellationToken ct as the last parameter and pass it on.
- EF Core: ToListAsync(ct), FirstOrDefaultAsync(ct), SaveChangesAsync(ct). The database command is cancelled too.
- HttpClient: await client.GetAsync(url, ct).
- Streams, channels, Task.Delay and SemaphoreSlim.WaitAsync all accept tokens.
3. Add timeouts by linking tokens
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
cts.CancelAfter(TimeSpan.FromSeconds(5));
var rates = await _http.GetFromJsonAsync<Rates>(url, cts.Token);
The call stops either when the client disconnects or after 5 seconds.
4. Handle cancellation correctly
- Let OperationCanceledException propagate; do not wrap it as a generic error.
- Do not log client disconnects as errors; check ct.IsCancellationRequested to tell them apart from your own timeouts.
- For CPU loops, call ct.ThrowIfCancellationRequested() periodically.
5. Know when not to cancel
- Work that must finish once started — committing a payment, writing an audit record — should not be cancelled halfway because the user navigated away. Use CancellationToken.None for that step or hand it off to a durable background queue.
- Background services use the stoppingToken from ExecuteAsync for graceful shutdown.
Benefits: less wasted database and CPU time, faster recovery under load, and timeouts that prevent requests from hanging.