6.48Canceling HTTP Requests with CancellationToken

Created on Aug 17, 2026~2 min read

The framework provides cancellation functionality for all methods that send HTTP remote requests, which can be achieved simply through the cancellationToken parameter. The following are examples of three ways to cancel requests:

  • Define a CancellationToken parameter in the controller Action:

When the user closes the browser or interrupts the request, the HTTP remote request operation can be canceled.

cs
[ApiController][Route("[controller]/[action]")]public class HttpRemoteController(IHttpRemoteService httpRemoteService) : ControllerBase{    [HttpGet]    public async Task<string?> GetContent(CancellationToken cancellationToken)    {        await httpRemoteService.GetAsAsync<string>("https://furion.net/", cancellationToken: cancellationToken);    }}
  • Use the HttpContext.RequestAborted property:

When the user closes the browser or interrupts the request, the HTTP remote request operation can be canceled.

cs
[ApiController][Route("[controller]/[action]")]public class HttpRemoteController(IHttpRemoteService httpRemoteService,    IHttpContextAccessor httpContextAccessor) : ControllerBase{    [HttpGet]    public async Task<string?> GetContent()    {        await httpRemoteService.GetAsAsync<string>("https://furion.net/"            , cancellationToken: httpContextAccessor.HttpContext.RequestAborted);    }}
  • Create a CancellationTokenSource object to cancel the request manually:

Creating a CancellationTokenSource instance allows precise control over when to cancel the HTTP request.

cs
[ApiController][Route("[controller]/[action]")]public class HttpRemoteController(IHttpRemoteService httpRemoteService) : ControllerBase{    [HttpGet]    public async Task<string?> GetContent()    {        using var cancellationTokenSource = new CancellationTokenSource();        cancellationTokenSource.CancelAfter(100);        await httpRemoteService.GetAsAsync<string>("https://furion.net/"            , cancellationToken: cancellationTokenSource.Token);    }}