【问题标题】:Getting the roles from the HttpContextBase从 HttpContextBase 获取角色
【发布时间】:2011-07-04 04:19:37
【问题描述】:

有没有办法从 HttpContextBase 中获取角色数组?

我正在寻找这样的课程:

    public static IList<string> GetUserRoles(this HttpContextBase context)
    {
        if (context != null)
        {

        }

        // return roles array;
    }

感谢您的帮助。

【问题讨论】:

    标签: asp.net asp.net-mvc role


    【解决方案1】:

    你可以使用:

    System.Web.Security.Roles.GetAllRoles()
    

    你想使用 HttpContextBase 的原因是什么?

    * 编辑 * 糟糕,我现在看到您想要给定用户的角色列表。 我以为你想要所有可用角色的列表。

    您可以遍历角色并检查哪些角色适用:

    HttpContextBase.User.IsInRole(role);
    

    【讨论】:

      【解决方案2】:

      您可能在 Application_AuthenticateRequest 中使用了 GenericPrincipal。我建议您创建一个公开一系列角色的自定义主体:

      public class CustomPrincipal: IPrincipal
      {
          public CustomPrincipal(IIdentity identity, string[] roles)
          {
              this.Identity = identity;
              this.Roles = roles;
          }
      
          public IIdentity Identity
          {
              get;
              private set;
          }
      
          public string[] Roles
          {
              get;
              private set;
          }
      
          public bool IsInRole(string role)
          {
              return (Array.BinarySearch(this.Roles, role) >= 0 ? true : false);  
          }
      } 
      

      现在您可以读取 cookie 并创建自定义主体。

          protected void Application_AuthenticateRequest(Object sender, EventArgs e)
          {
              HttpCookie authCookie = Request.Cookies[My.Application.FORMS_COOKIE_NAME];
              if ((authCookie != null) && (authCookie.Value != null))
              {
                  var identity = new GenericIdentity(authTicket.Name, "FormAuthentication");
                  var principal = new CustomPrincipal(identity, Roles, Code);
                  Context.User = principal;
              }
          }
      

      你的函数看起来像这样:

          public static IList<string> GetUserRoles(this HttpContextBase context)
          {
              if (context != null)
              {
                  return(((CustomPrincipal)context.User).Roles);
              }
      
              return (null);
              // return roles array;
          }
      

      【讨论】:

        猜你喜欢
        • 2021-09-30
        • 2012-06-11
        • 2021-04-07
        • 2017-10-18
        • 2022-01-02
        • 1970-01-01
        • 2011-11-29
        • 2022-11-23
        • 2010-12-31
        相关资源
        最近更新 更多