在布局视图中获取当前 ApplicationUser

Get current ApplicationUser in layout view

我正在使用 MVC5,创建 ApplicationUser : IdentityUser 具有自定义属性。现在我想在 layout.cshtml 中获得自定义 属性(头像)以在不同布局(header、侧边栏)视图中显示登录用户图像。我该怎么做?

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

}

目前我正在使用 @User.Identity.Name 在我的视图中获取登录的用户名。我也想要用户形象。

我怎样才能得到它?

您可以添加头像 属性 作为 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;
     }
}

在剃须刀视图中,您可以像这样访问它

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