【发布时间】:2017-09-08 11:46:39
【问题描述】:
我正在尝试将扩展属性添加到 User.Identity 并执行以下操作:
在 IdentityModel.cs 我添加了一个名为 EbrowAdmin 的字段:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
userIdentity.AddClaim(new Claim("EbrowAdmin", EbrowAdmin.ToString()));
return userIdentity;
}
public bool EbrowAdmin { get; set; }
我在 Project 文件夹中创建了一个名为 Extensions 的文件夹,并添加了一个名为 Extensions.cs 的类:
public static class Extensions
{
public static string GetEbrowAdmin(this IIdentity identity)
{
var claim = ((ClaimsIdentity)identity).FindFirst("EbrowAdmin");
// Test for null to avoid issues during local testing
return (claim != null) ? claim.Value : string.Empty;
}
}
现在我可以从我的控制器访问这个新属性:
User.Identity.GetEbrowAdmin();
但是我无法使用相同的代码从我的视图中访问它:
@User.Identity.GetEbrowAdmin();
任何想法我缺少什么?
【问题讨论】:
标签: asp.net-mvc model-view-controller asp.net-identity claims-based-identity