从视图访问User.Identity属性扩展(错误)

时间:2017-09-08 11:46:39

标签: asp.net-mvc model-view-controller asp.net-identity claims-based-identity

我正在尝试向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();

我缺少什么想法?

1 个答案:

答案 0 :(得分:1)

您需要告诉您对扩展程序的看法。就像普通的C#代码一样,在您使用using指令包含代码的命名空间之前,视图不会发现任何自定义代码。

尝试在您的直接视图或viewstart.cshtml中放置using <YOURPROJECT>.<YOURNAMESPACE>.Extensions

相关问题