ASP.NET Core MVC Interview Question #97
What is the difference between synchronous and asynchronous MVC filters?
Advanced Routing, Filters, Areas & Application Structure Mid-Level Intermediate
Quick Interview Answer
MVC provides synchronous filter interfaces such as IActionFilter and asynchronous equivalents such as IAsyncActionFilter. An asynchronous filter should be used when its work requires asynchronous I/O.
Detailed Explanation
MVC provides synchronous filter interfaces such as IActionFilter and asynchronous equivalents such as IAsyncActionFilter. An asynchronous filter should be used when its work requires asynchronous I/O.
Async filters call and await the provided continuation delegate to execute the next stage. Avoid blocking asynchronous operations with .Result or .Wait() inside filters.
Code Example
public sealed class AuditFilter : IAsyncActionFilter
{
public async Task OnActionExecutionAsync(
ActionExecutingContext context,
ActionExecutionDelegate next)
{
await WriteAuditStartAsync();
var executed = await next();
await WriteAuditEndAsync(executed);
}
}