【发布时间】: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()));
如何在视图中轻松获取它?
【问题讨论】:
-
这可能会有所帮助Custom Identity & Principal
标签: asp.net-mvc cookies claims-based-identity