Difference between OnActionExecting and OnActionExecutingAsync
The difference is OnActionExecuting runs SYNCHRONOUSLY and OnActionExecutingAsync should be used when you want to run some ASYNCHRONOUS calls.
OnActionExecuting Implementation
public class ActionFilter : Attribute, IActionFilter
{
private ILoggerEntry _loggerEntry;
public ActionFilter(ILoggerEntry loggerEntry)
{
_loggerEntry = loggerEntry ?? throw new ArgumentNullException("ILogger cannot be null");
}
public void OnActionExecuted(ActionExecutedContext actionContext)
{
_loggerEntry.AddToLog("Called after action method executes");
}
public void OnActionExecuting(ActionExecutingContext actionContext)
{
_loggerEntry.AddToLog("Called before action method executes. Executed Synchronously");
}
}
OnActionExecutingAsync Implementation
Use this when you want to add await statements to call asynchronous methods.
public class ActionFilterAsync : Attribute, IAsyncActionFilter
{
private ILoggerEntry _loggerEntry;
public ActionFilterAsync(ILoggerEntry loggerEntry)
{
_loggerEntry = loggerEntry ?? throw new ArgumentNullException("ILogger cannot be null");
}
public async Task OnActionExecutionAsync(ActionExecutingContext actionContext, ActionExecutionDelegate next)
{
_loggerEntry.AddToLog("Called before action method executes. Executed Asynchronously");
await _loggerEntry.LogErrorEntry();
await next();
}
}
Now, you can invoke the attribute on a controller or any controller action method.
[ApiController]
[Route("[controller]")]
[ServiceFilter(typeof(ActionFilter))]
public class WeatherForecastController : ControllerBase
Comments
Post a Comment