Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionFilterAttribute: When to use OnActionExecuting vs. OnActionExecutingAsync?

I made a LoggedAttribute class that inherited from System.Web.Http.Filters.ActionFilterAttribute and put logging into OnActionExecuting and OnActionExecutingAsync methods; I had assumed one would be used for async calls and one would be used for non-async calls, but it seems both are being used. So which one should I put my logging 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);
    }
}

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

like image 753
Jeremy Holovacs Avatar asked Jan 26 '16 22:01

Jeremy Holovacs


1 Answers

The reply doesn't answer the question I think,

Both are used if you need to run your code before executing the action.

If you want it also to be ran SYNCHRONOUSLY use OnActionExecuting, otherwise use OnActionExecutingAsync (e.i. Async).

like image 137
A77 Avatar answered Sep 24 '22 07:09

A77