从视图访问 User.Identity 属性 扩展(错误)
Access User.Identity property extension from a View (Error)
我正在尝试向 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; }
我在项目文件夹中创建了一个名为 Extensions 的文件管理器,并添加了一个名为 Extensions.cs:
的 class
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();
知道我遗漏了什么吗?
你需要说说你对你的扩展的看法。就像普通的 C# 代码一样,在使用 using 指令包含代码的命名空间之前,视图不知道任何自定义代码。
尝试将 using <YOURPROJECT>.<YOURNAMESPACE>.Extensions
放在您的直接视图或 viewstart.cshtml
中
我正在尝试向 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; }
我在项目文件夹中创建了一个名为 Extensions 的文件管理器,并添加了一个名为 Extensions.cs:
的 class 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();
知道我遗漏了什么吗?
你需要说说你对你的扩展的看法。就像普通的 C# 代码一样,在使用 using 指令包含代码的命名空间之前,视图不知道任何自定义代码。
尝试将 using <YOURPROJECT>.<YOURNAMESPACE>.Extensions
放在您的直接视图或 viewstart.cshtml