Search code examples
c#asp.net-web-apiaction-filter

Get User Name on Action Filter


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

Solution

  • You can try

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
            {
               string username = HttpContext.Current.User.Identity.Name;
            }
    

    Check for authenticated user first:

    string userName = null;
    if (HttpContext.Current.User.Identity.IsAuthenticated)
    {
        userName = HttpContext.Current.User.Identity.Name;
    }
    

    Try to use

    HttpContext.Current.User.Identity.Name
    

    Hope it works for you