ActionFilterAttribute: When to use OnActionExecuting vs OnActionExecutingAsync?

I created the LoggedAttribute class inherited from System.Web.Http.Filters.ActionFilterAttribute and injected logging into the OnActionExecuting and OnActionExecutingAsync ; I assumed that one will be used for asynchronous calls, and one will be used for non-asynchronous calls, but it seems that both of them are used. So what should I put my journal in?

UPDATE

Code follows:

 public sealed class LoggedAttribute : ActionFilterAttribute { private readonly ILog _logger; public LoggedAttribute(ILogManager logManager) { _logger = logManager.GetLogger<LoggedAttribute>(); } public LoggedAttribute() : this(new LogManager()) {} public override void OnActionExecuting(HttpActionContext actionContext) { //logging logic goes here base.OnActionExecuting(actionContext); } public override async Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) { //logging logic goes here await base.OnActionExecutingAsync(actionContext, cancellationToken); } } 

Then I apply the [Logged] attribute to my base ApiController, and I get duplicate log entries for single calls.

+5
source share
2 answers

Well, it looks like OnActionExecuting is called on every single request. I put my logic exclusively in this method and it seems to work as I wish.

+2
source

The answer does not answer the question that I think

Both are used if you need to run your code before performing an action.

If you want it to also be executed SYNCHRONOUSly , use OnActionExecuting , otherwise use OnActionExecutingAsync (ei Async).

+8
source

Source: https://habr.com/ru/post/1241555/


All Articles