Shawn Mclean
Shawn Mclean

Reputation: 57469

User Identity in asp.net mvc

I need to get the user's name and ID to be accessible in my view. When I use Page.User.Identity.Name, I get the email I use to authenticate it. This is how I go about authenticating the user from my controller:

if (!userService.ValidateUser(model.Email, model.Password))
      FormsAuthentication.SetAuthCookie(model.Email, false);

How can I be able to do: Page.User.Identity.UserId or Page.User.Identity.FirstName?

Upvotes: 0

Views: 9023

Answers (2)

uvita
uvita

Reputation: 4124

Shaun, here´s an idea:

First, you can create an action filter so that you inject the object that represents your user in the ViewData collection. You can apply this attribute to your controller or to the actions.

public class AddUserToViewDataAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var email = filterContext.HttpContext.User.Identity.Name;

        var user = _userService.GetUser(email);

        filterContext.Controller.ViewData["CurrentUser"] = user;
    }
}

Some improvements should be made of course, this is just an idea.

Another idea is to create a base controller class (so that your controllers extend it) and in that controller you can have a method (e.g. GetCurrentUser) that does the same as in this filter (i.e. load the user from the DB). You can apply some caching like for example, saving the user object in the HttpContext.Items collection.

Cheers.

Upvotes: 3

Ryan
Ryan

Reputation: 4313

The base MVC controller has a User property you can access in your actions. Just attach the properties you need to your view model.

public ActionResult Index()
{  
   var user = new UserViewModel();
   user.FirstName = this.User.Identity.FirstName;
   ViewData["UserDetails"] = user;
   // ...
   return View(theOtherModel);
}

In the site.master:

<% var userModel = ViewData["UserDetails"] as UserViewModel; %>
Hello <%: userModel.FirstName  %>!

Upvotes: 3

Related Questions