2011-02-25 89 views
1

有一種方法可以從HttpContextBase獲取角色數組?從HttpContextBase獲取角色

我希望做的一類這樣的:

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

     } 

     // return roles array; 
    } 

感謝您的幫助。

回答

3

您可以使用:

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; 
    }