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

  • How can I get the id of the currently logged in user in MVC 5? I tried the StackOverflow suggestions, but they seem to be not for MVC 5.
  • Also, what is the MVC 5 best practice of assigning stuff to the users? (e.g. a User should have Items. Should I store the User's Id in Item? Can I extend the User class with an List<Item> navigation property?

I'm using "Individual User Accounts" from the MVC template.

Tried these:

  • How do I get the current user in an MVC Application?
  • How to get the current user in ASP.NET MVC
  • Get logged in user's id - this throws the following:

'Membership.GetUser()' is null.


Solution 1:

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:

  • Overview of Identity: https://devblogs.microsoft.com/aspnet/introducing-asp-net-identity-a-membership-system-for-asp-net-applications/
  • Example solution regarding how to extend the user profile by adding an extra property: https://github.com/rustd/AspnetIdentitySample

Solution 2:

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.