Rehan Shah
Rehan Shah

Reputation: 1627

How to get current logged-In User details?

I added to new properties to ApplictionUser and now i want to retrieve it ?

public class ApplicationUser : IdentityUser
{
   [Required]
   [StringLength(50)]
   public string FirstName { get; set; }

   [Required]
   [StringLength(50)]
   public string LastName { get; set; }

   //....
}

I tried to retrieved by using User.Identity... but i can't get first&last names?

How to do that ? I shall be very thankful.

Upvotes: 1

Views: 265

Answers (2)

Rehan Shah
Rehan Shah

Reputation: 1627

I retrieved the firstName and SecondName in this way:

Step 1.

// DbContext.
private readonly ApplicationDbContext _context;

public HomeController()
{
   _context = new ApplicationDbContext();
}

Step 2.

// Getting Id of Current LoggedIn User.
var UserId = User.Identity.GetUserId();

Step 3.

var User = _context.Users.Single(user => user.Id == UserId);

These steps worked for me.

Upvotes: 3

AlbertK
AlbertK

Reputation: 13227

User.Identity returns just an abstraction System.Security.Principal.IIdentity that doesn't contain any custom properties and ApplicationUser instance.

One of the option is to use UserManager<ApplicationUser> that can be injected into the controller if you Startup class has config for ASP.NET Core Identity:

var user = await _userManager.FindByIdAsync(userId);

It will return exactly ApplicationUser instance.

Another option is get the user from your DbContext directly (by default its name is ApplicationDbContext. It also can be injected into the controller).

var user = await db.Users.SingleOrDefaultAsync(u => u.Id == userId);

Upvotes: 2

Related Questions