Get User Name on Action Filter

TamarG picture TamarG · May 20, 2013 · Viewed 36.8k times · Source

I use MVC4 web application with Web API. I want to create an action filter, and I want to know which user (a logged-in user) made the action. How can I do it?

public class ModelActionLog : ActionFilterAttribute
{
    public override void OnActionExecuting(SHttpActionContext actionContext)
    {
       string username = ??
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
       ??
    }
}

Answer

Atul Chaudhary picture Atul Chaudhary · May 28, 2015

Bit late for an answer but this is best solution if you are using HttpActionContext in your filter You can always use it as mentioned here:-

public override Task OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
   if (actionContext.RequestContext.Principal.Identity.IsAuthenticated)
   {
      var userName = actionContext.RequestContext.Principal.Identity.Name;
   }
}