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.
Is CancellationToken available in ASP.NET Core ActionFilter?
Asked Answered
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 theCancellationTokenModelBinder
.
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
}
}
© 2022 - 2024 — McMap. All rights reserved.
CancellationToken
into ASP.NET Core action method..." – LittmanCancellationToken
is being instantiated and provided byinterface injection
as an action method argument by ASP.NET Core the same way as some IoC container could doconstructor injection
of other dependencies it is responsible for. – GiveCancellationToken
parameters in an action method to theHttpContext.RequestAborted
token, using theCancellationTokenModelBinder
. This model binder is registered automatically when you callservices.AddMvc()
(orservices.AddMvcCore()
) inStartup.ConfigureServices()
." – Littmancontext.HttpContext.RequestAborted
token within yourIActionFilter.OnActionExecuting(ActionExecutingContext context)
method – Littman