Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to create a filter for CancellationToken for all actions?

I want to create an ASP.NET Core WebApi Service where every actions supports a CancellationToken without explicitly implementing it with a parameter.

I don't want to do this for every action:

[HttpGet]
public async Task<IEnumerable<string>> Get(CancellationToken token = default)
{
    return await DoStuffAsync(token);
}

I want to be able to do this:

[HttpGet]
public async Task<IEnumerable<string>> Get()
{
    return await DoStuffAsync(_contextManager.Token);
}

Where _contextManager extracts the CancellationToken from the action. Would this be possible with a custom IActionFilter or another way?

like image 322
Tobias Thieron Avatar asked Sep 05 '25 16:09

Tobias Thieron


1 Answers

The CancellationToken passed into actions is bound using CancellationTokenModelBinder, which uses HttpContext.RequestAborted as the value. You can use this yourself, directly, like this:

[HttpGet]
public async Task<IEnumerable<string>> Get()
{
    return await DoStuffAsync(HttpContext.RequestAborted);
}
like image 95
Kirk Larkin Avatar answered Sep 08 '25 14:09

Kirk Larkin