Get current ApplicationUser in layout

I am using MVC5 created by ApplicationUser : IdentityUser with custom properties. Now I want to get a custom property (Avatar) in layout.cshtml to show the registered user image in different layouts (header, sidebar). How to do it?

 public class ApplicationUser : IdentityUser { public string Avatar { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); return userIdentity; } } 

I am currently using @User.Identity.Name to get the username in my views. I also want a user image.

How can i get this?

+6
source share
1 answer

You can add an avatar property as IdentityClaim

 public class ApplicationUser : IdentityUser { public string Avatar { get; set; } public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); userIdentity.AddClaim(new Claim("avatar", this.Avatar)); return userIdentity; } } 

Inside the razor view, you can access it as follows

 @{ var avatar = ((ClaimsIdentity)User.Identity).FindFirst("avatar"); } 
+8
source

Source: https://habr.com/ru/post/986529/


All Articles