Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is CancellationToken available in ASP.NET Core ActionFilter?

I could inject CancellationToken into ASP.NET Core action method, but I would instead prefer to work with it using action filter. How to get access to cancellation token while implementing IAsyncActionFilter? My method should not have it as a parameter then.

like image 800
Dmitry Nogin Avatar asked Mar 03 '23 08:03

Dmitry Nogin


1 Answers

You already post a link to a very good article, which contains a small hint where you can get this token.

MVC will automatically bind any CancellationToken parameters in an action method to the HttpContext.RequestAborted token, using the CancellationTokenModelBinder.

So, all you have to do is acquire that token in your action filter:

public class CustomActionFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        var cancellationToken = context.HttpContext.RequestAborted;
        // rest of your code
    }
}
like image 99
vasily.sib Avatar answered Mar 23 '23 10:03

vasily.sib