2011-02-25 85 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; 
    }