C# – Get User Name on Action Filter

action-filterasp.net-web-apic

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)
    {
       ??
    }
}

Best Answer

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;
   }
}
Related Topic