【问题标题】:Access User.Identity property extension from a View (Error)从视图访问 User.Identity 属性扩展(错误)
【发布时间】: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


    【解决方案1】:

    您需要说明您对扩展程序的看法。就像普通的 C# 代码一样,视图不知道任何自定义代码,直到您使用 using 指令包含代码的命名空间。

    尝试在您的直接视图或 viewstart.cshtml 中添加 using &lt;YOURPROJECT&gt;.&lt;YOURNAMESPACE&gt;.Extensions

    【讨论】:

    • 是的,你是对的 - 解决了它。我已经在我的 Views/Web.config 中添加了命名空间扩展,但由于某种原因这不起作用......但是将 using 指令直接添加到 View 就可以了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2015-04-04
    • 2015-07-23
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 2016-12-06
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多