Lock
Lock

Reputation: 5522

How to get user object of currently logged in user

What is the correct way to get an Identity User Object (from the identity framework) of the currently logged in user in a controller?

I need to update some properties against the user (table AspNetUsers) and do not know the correct method of getting the user object so that I could do things such as:

  var menuItem = context.MenuItems.First(m => m.Description == "New Order");
  var user = ??????????
  user.MenuItems.Add(menuItem);
  context.SaveChanges();

I've slightly modified the original user model by adding a few properties and renaming the class:

public class User : IdentityUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User> manager)
    {
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }
    public virtual ICollection<MenuItem> MenuItems { get; set; }
}

So how can I retrieve this User object from my controllers?

Upvotes: 1

Views: 5994

Answers (2)

DSR
DSR

Reputation: 4658

Get username

var userName = User.Identity.Name;

Get the user using static method created below.

var user = GetCurrentUser(userName);

Static method to get user

            public static User GetCurrentUser(string userName)
            {
                var userManager = new UserManager<User>(new UserStore<User>(new YourIdentityDbContext()));
                var user = userManager.FindByName(userName);
                return user;
            }

Upvotes: 0

Xavier Egea
Xavier Egea

Reputation: 4763

In the controller class use the namespace Microsoft.AspNet.Identity and the get the current user like this:

var user = User.Identity;

Example:

using Microsoft.AspNet.Identity;
...
public class FooController : Controller
{
    [Authorize]
    public ActionResult Index()
    {
        var user = User.Identity;
        ...
        return View();
    }
}

Edited

Getting Profile Information: This link gives the steps to add profile information to your user.

To retrieve your user data you should:

  1. Get the current logged in UserId, so you can look the user up in ASP.NET Identity system

var currentUserId = User.Identity.GetUserId();

  1. Instantiate the UserManager in ASP.Identity system so you can look up the user in the system

var manager = new UserManager(new UserStore(new MyDbContext()));

  1. Get the User object

var currentUser = manager.FindById(User.Identity.GetUserId());

  1. Get the profile information about the user

currentUser.MyUserInfo.FirstName

Upvotes: 3

Related Questions