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

6
我正在使用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;
    }

}

目前我正在使用@User.Identity.Name在我的视图中获取已登录用户的名称。我还想要用户的头像。

我该如何获取它呢?


我不确定,但你能先将对象转换一下吗?@(((AppliactionUser)User.Identity).Avatar) 我通过创建一个包含我的用户类的基本视图模型来解决了这个问题。我在我的布局中使用基类来多次使用多个属性。 - Martin
@Martin 不起作用。抛出“无法将类型为'System.Security.Claims.ClaimsIdentity'的对象强制转换为类型”的异常。 - SMUsamaShah
然后我会创建一个基础视图模型,您可以在每个视图模型中使用它。这将使您能够访问布局页面中所需的所有属性。 - Martin
1个回答

11

你可以将 avatar 属性作为 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;
     }
}

在 Razor 视图中,您可以像这样访问它

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

2
avatar.Value 包含的是该数值。 - SMUsamaShah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接