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

twaldron picture twaldron · Oct 19, 2011 · Viewed 7.6k times · Source

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?

Answer

Darin Dimitrov picture Darin Dimitrov · Oct 19, 2011
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;
}