Advertisement
Advanced ASP.NET Core, Filters

How does an IAsyncActionFilter differ from the synchronous IActionFilter, and why is the async version generally preferred for filters doing I/O work?

Short answer

IAsyncActionFilter's single OnActionExecutionAsync method receives an ActionExecutionDelegate you explicitly await to continue the pipeline (giving you a single, clear place for both before and after logic wrapping the call), whereas IActionFilter's…

Save ASP.NET Core mock interview
Advertisement
AModel answer
IAsyncActionFilter's single OnActionExecutionAsync method receives an ActionExecutionDelegate you explicitly await to continue the pipeline (giving you a single, clear place for both before and after logic wrapping the call), whereas IActionFilter's OnActionExecuting/OnActionExecuted pair are synchronous methods -- for filters performing I/O (a database call to check a feature flag, an external API call), the async variant avoids blocking a thread pool thread during that I/O, just as async/await matters anywhere else in the request pipeline.
public class FeatureFlagFilter(IFeatureFlagService flags) : IAsyncActionFilter {
    public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) {
        if (!await flags.IsEnabledAsync("NewCheckout")) {
            context.Result = new NotFoundResult();
            return;  // short-circuits, next() never called
        }
        await next();  // continue to the action
    }
}
Real-world example
A feature-flag-checking filter uses the async variant since it needs to call an external feature flag service, avoiding blocking a thread pool thread during that network call the way a synchronous filter making a blocking call would.
Likely follow-ups
  • What happens if you don't call next() inside OnActionExecutionAsync?
  • Can you inspect or modify the action's result after next() returns?
Related topics