Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 887
twaldron Avatar asked Oct 19 '11 17:10

twaldron


People also ask

How can get current user in ASP.NET MVC?

If you need to get the user from within the controller, use the User property of Controller. If you need it from the view, I would populate what you specifically need in the ViewData , or you could just call User as I think it's a property of ViewPage .

Which string is used to obtain the user name of the current user inside an ASP.NET MVC web application?

string username = currentUser. UserName; //Get UserId of Currently logged in user.

What is the use of Actionfilters in MVC?

ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.

How are custom filters implemented in MVC?

You can create custom filter attributes by implementing an appropriate filter interface for which you want to create a custom filter and derive the FilterAttribute class to use that class as an attribute. For example, implement IExceptionFilter and the FilterAttribute class to create a custom exception filter.


1 Answers

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;
}
like image 186
Darin Dimitrov Avatar answered Oct 10 '22 17:10

Darin Dimitrov