【问题标题】:ASP.NET MVC 5 Pass/Get more user data to the whole applicationASP.NET MVC 5 向整个应用程序传递/获取更多用户数据
【发布时间】:2015-05-21 13:03:30
【问题描述】:

我在继承自 IdentityUser 的用户模型中添加了一些新列:

public class ApplicationUser : IdentityUser
{

    public int Age { get; set; }
    public bool Sex { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        //userIdentity.AddClaim(new Claim("age", this.Age.ToString()));

        return userIdentity;
    }

}

默认情况下我只能获取用户名,如_LoginPartial.cshtml所示:

@Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })

我想从 User.Identity 获取自定义信息,例如年龄和性别。我发现实施和使用声明的解决方案非常奇怪,一旦我要在每个页面中显示它,我就无法使其全局化。

如果这样做的方法是添加这样的声明:

userIdentity.AddClaim(new Claim("age", this.Age.ToString()));

如何在视图中轻松获取它?

【问题讨论】:

标签: asp.net-mvc cookies claims-based-identity


【解决方案1】:

我发现用户会话 cookie 更容易,因此在 AccountController.cs 中,我在 case SignInStatus.Success 中添加了两行:

var user = SignInManager.UserManager.FindByEmail(model.Email);
Session["userInfo"] = user.Age;

然后我可以调用 _LoginPartial.cshtml 例如:

 @{
    if (Session["userInfo"] != null)
    {
        var age = Session["userInfo"];
        <li>@Html.ActionLink("Age: " + age.ToString(), "Index", "Albums")</li>
    }
}

【讨论】:

    【解决方案2】:

    这来自 WebpageRenderingBase,它有一个 IPrincipal 用户属性。

    IPrincipal 定义了一个 Identity 属性,该属性提供对实现接口 IIdentity 的类型的项目的访问权限。

    因此,您希望返回的 @User.Identity IIndentity 实际上可能是 ApplicationUser,如果是,那么您可以将其强制转换为此类,然后访问其他属性。强>

    如果这是真的,那么你已经完成了。如果不是,则需要先通过其他方式获取ApplicationUser。

    所以最大的问题是:实现 IIdentity 接口的项目是什么实际的类型,你已经拥有了?

    @if( User.Identity is ApplicationUser)
    {
      <text>
        @(((ApplicationUser)User.Identity).Age)
      </text>
    }
    else 
    {
      //GoFish
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-28
      相关资源
      最近更新 更多