【问题标题】:MVC 5 - Add Methods to @User from ViewMVC 5 - 从视图中向@User 添加方法
【发布时间】:2020-06-08 05:38:01
【问题描述】:

从开箱即用的 cshtml 页面中,您可以使用 User.IsInRole() 检查用户是否在角色内。在我的应用程序中,我使用自定义 IIdentity 用户并实现我自己的 UserStore、UserManager、RoleManager 等。

在我的自定义身份上,我为应用程序等添加自定义声明。

public async Task<ClaimsIdentity> GenerateUserIdentityAsync( UserManager<CustomIdentity, int> 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( CustomClaimTypes.Application, "Application1" ) );

            return userIdentity;
        }

如何向 User 或 User.Identity 添加其他方法,例如 User.HasApplication("string")

【问题讨论】:

    标签: model-view-controller asp.net-identity


    【解决方案1】:

    您可以通过以下方式创建扩展类访问

    public static class IdentityExtensions
        {
            public static bool GetIdentityExtentsion(this IIdentity identity)
            {
                return true;
            }
    
            public static bool GetIdentityExtentsion2( this IPrincipal principal )
            {
                return true;
            }
    
        }
    

    GetIdentityExtentsion 将可见 @User.Identity.GetIdentityExtensions

    GetIdentityExtensions2 将可见 @User.GetIdentityExtensions2

    确保在视图中添加@using 命名空间。我已经在 Views / Web.Config 中尝试过,但由于某种原因它没有显示扩展。

    【讨论】:

      猜你喜欢
      • 2015-04-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 2015-04-03
      • 2016-06-08
      • 1970-01-01
      相关资源
      最近更新 更多