Search code examples
asp.net-mvcaction-filter

ASP.NET MVC finding the current username in a custom action filter


I am creating a custom action filter for asp.net MVC.

In the OnActionExecuting() method.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    string userName =  ?????// how can I get this?
}   

I need to find out the current users name (I am using forms authentication)

In the controller I can simply just do User.Identity.Name

Is there a way to get the users name in the ActionFilter?


Solution

  • string userName = filterContext.HttpContext.User.Identity.Name;
    

    And if you wanted to check if there is an authenticated user first:

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