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?
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 .
string username = currentUser. UserName; //Get UserId of Currently logged in user.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With