Search code examples
c#asp.net-mvc-5asp.net-identityfindnameusermanager

Getting the ApplicationUser object in a controller


I am writing a C# MVC5 internet application and am having some trouble getting the ApplicationUser object in a controller that I have created.

Here is my code:

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

When I try to run this code, when a user is logged in, I am getting a null object for the ApplicationUser user.

Can I please have some help with this?

Thanks in advance


Solution

  • FindByNameAsync() expects a username but you're passing the user id. Either pass the username...

    ApplicationUser user = userManager.FindByNameAsync(User.Identity.GetUserName()).Result;
    

    Or use the FindByIdAsync() method...

    ApplicationUser user = userManager.FindByIdAsync(User.Identity.GetUserId()).Result;