Reputation: 5522
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
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
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:
var currentUserId = User.Identity.GetUserId();
var manager = new UserManager(new UserStore(new MyDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
currentUser.MyUserInfo.FirstName
Upvotes: 3