【问题标题】:ASP.NET custom RoleProvider - use of cookiesASP.NET 自定义 RoleProvider - cookie 的使用
【发布时间】:2012-04-16 08:15:22
【问题描述】:

目前在登录时,我正在为用户插入一行到 AccessSession 表中,该表保留了用户具有哪些角色以及 ASP.NET_SessionId cookie 的详细信息。

我的 GetRolesForUser 方法的自定义实现是:

public override string[] GetRolesForUser(string username)
    {
        List<string> roles = new List<string>();
        string[] rolesArray;
        char[] splitter = { '|' };            

        string sessionId = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value;
        AccessSession sessionObject = AccessSession.Get(sessionId);

        if (sessionObject != null)
        {
            rolesArray = sessionObject.Roles.Split(splitter);

            foreach (string role in rolesArray)
            {
                if (!String.IsNullOrEmpty(role))
                {
                    roles.Add(role);
                }
            }
        }
        return roles.ToArray();
    }

我的问题是我使用这种方法错了吗?如果 cookie 被禁用,那么将没有 HttpContext.Current.Request.Cookies["ASP.NET_SessionId"]。我的替代计划是在 Session 中插入一个 AccessSession 对象,但是当自定义 RoleProvider 尝试访问它时,它总是显示为 null。

我可以使用 cacheRolesInCookie=true 但同样,这并不比上述方法更好,因为禁用 cookie 会破坏功能。

谢谢, 理查德

【问题讨论】:

    标签: asp.net asp.net-membership membership-provider roleprovider


    【解决方案1】:

    好吧,我最终通过从 FormsAuthenticationTicket 中获取角色来解决这个问题,FormsAuthenticationTicket 已经包含了我的所有角色。下面是代码示例:

    public override string[] GetRolesForUser(string username)
        {
            List<string> roles = new List<string>();
            string[] rolesArray = new string[] { };
            char splitter = Advancedcheck.BLL.Common.Const.default_splitter;
    
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket = id.Ticket;
    
                        rolesArray = ticket.UserData.Split(splitter);
    
                        HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(id, rolesArray);
                    }
                }
            }
    
            if (rolesArray.Length > 0)
            {
                foreach (string role in rolesArray)
                {
                    if (!String.IsNullOrEmpty(role))
                    {
                        roles.Add(role.ToLower());
                    }
                }
            }
            return roles.ToArray();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-29
      相关资源
      最近更新 更多