21

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?

1 Answer 1

46
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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Well that was incredibly easy, not sure why I has such a hard time finding it. Thank you once again Darin!
@DarinDimitrov How to get UserId instead of name? In controller action, I can simply use User.Identity.GetUserId();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.