2

目前在登錄時,我將用戶行插入到AccessSession表中,該表保留了用戶與ASP.NET_SessionId cookie一起使用的角色的詳細信息。ASP.NET自定義RoleProvider - 使用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(); 
    } 

我的問題是我錯了使用這種方法?如果cookies被禁用,那麼將不會有HttpContext.Current.Request.Cookies [「ASP.NET_SessionId」]。我的替代方案是在Session中插入一個AccessSession對象,但當自定義RoleProvider試圖訪問它時,它總是顯示爲空。

我可以使用cacheRolesInCookie = true,但再次,這將不會比上述方法更好,因爲禁用cookie會破壞功能。

感謝, 理查德

回答

3

嗯,我設法讓從舉辦已經是我所有角色中的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(); 
    } 
相關問題