在布局视图中获取当前的ApplicationUser

SMU*_*hah 6 asp.net-mvc asp.net-identity

我正在使用MVC5,ApplicationUser : IdentityUser使用自定义属性创建.现在我想在layout.cshtml中获取一个自定义属性(Avatar),以在不同的布局(标题,侧边栏)视图中显示登录的用户图像.我怎么做?

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

}
Run Code Online (Sandbox Code Playgroud)

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

我怎么能得到它?

tmg*_*tmg 9

您可以添加头像属性作为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;
     }
}
Run Code Online (Sandbox Code Playgroud)

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

@{
    var avatar = ((ClaimsIdentity)User.Identity).FindFirst("avatar");
}
Run Code Online (Sandbox Code Playgroud)

  • `avatar.Value`包含值 (2认同)