Simon
Simon

Reputation: 8357

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

Upvotes: 0

Views: 1177

Answers (1)

Anthony Chu
Anthony Chu

Reputation: 37520

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;

Upvotes: 3

Related Questions