How to get current user, and how to use User class in MVC5? How to get current user, and how to use User class in MVC5? asp.net asp.net

How to get current user, and how to use User class in MVC5?


If you're coding in an ASP.NET MVC Controller, use

using Microsoft.AspNet.Identity;...User.Identity.GetUserId();

Worth mentioning that User.Identity.IsAuthenticated and User.Identity.Name will work without adding the above mentioned using statement. But GetUserId() won't be present without it.

If you're in a class other than a Controller, use

HttpContext.Current.User.Identity.GetUserId();

In the default template of MVC 5, user ID is a GUID stored as a string.

No best practice yet, but found some valuable info on extending the user profile:


Try something like:

var store = new UserStore<ApplicationUser>(new ApplicationDbContext());var userManager = new UserManager<ApplicationUser>(store);ApplicationUser user = userManager.FindByNameAsync(User.Identity.Name).Result;

Works with RTM.


If you want the ApplicationUser object in one line of code (if you have the latest ASP.NET Identity installed), try:

ApplicationUser user = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>().FindById(System.Web.HttpContext.Current.User.Identity.GetUserId());

You'll need the following using statements:

using Microsoft.AspNet.Identity;using Microsoft.AspNet.Identity.Owin;