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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With