CodingNeed.

3 · Reliability and delivery · 30 MIN

Cancellation and safe error responses

Request cancellation should reach asynchronous work.

A CancellationToken endpoint parameter binds to the request’s aborted signal. Passing it to Task.Delay or a real asynchronous dependency lets abandoned work stop cooperatively. AddProblemDetails with the exception handler gives unexpected failures a consistent response format without making endpoint code catch every exception. Production logging should retain enough correlation to investigate failures while omitting secrets. Cancellation is not a normal successful result, and swallowing OperationCanceledException can misrepresent an aborted operation.

Confirm the token reaches the service operation.

Read the example

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder=WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app=builder.Build();
app.UseExceptionHandler();
app.MapGet("/slow",async (CancellationToken ct)=>{
  await Task.Delay(TimeSpan.FromSeconds(3),ct);
  return new {ready=true};
});
app.Run();
Check the expected output
A completed /slow request returns {"ready":true} after approximately three seconds. Aborting the client cancels the delay.

Your challenge

Propagate cancellation into an injected service and test client abort separately from a simulated dependency exception.

Solution cost: O(1) application work plus asynchronous delay or dependency latency. time · O(1) per pending demonstration request. space

Common trap

Receiving a token but omitting it from downstream calls leaves abandoned work running.

Study the project implementation
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
var builder=WebApplication.CreateBuilder(args);
builder.Services.AddProblemDetails();
var app=builder.Build();
app.UseExceptionHandler();
app.MapGet("/slow",async (CancellationToken ct)=>{
  await Task.Delay(TimeSpan.FromSeconds(3),ct);
  return new {ready=true};
});
app.Run();

Further reading: Official documentation

Next lesson: Project · An API with integration tests

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.