Is CancellationToken available in ASP.NET Core ActionFilter?

Viewed 1560

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.

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
    }
}
Related