Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current ApplicationUser in layout view

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

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;
    }

}

Currently I am using @User.Identity.Name to get logged user name in my views. I also want the user image.

How can I get that?

like image 918
SMUsamaShah Avatar asked May 04 '15 20:05

SMUsamaShah


1 Answers

You can add 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 razor view you can access it like this

@{
    var avatar = ((ClaimsIdentity)User.Identity).FindFirst("avatar");
}
like image 153
tmg Avatar answered Oct 14 '22 07:10

tmg