有一种方法可以从 HttpContextBase 获取角色数组吗?
我正在寻找这样的课程:
public static IList<string> GetUserRoles(this HttpContextBase context)
{
if (context != null)
{
}
// return roles array;
}
谢谢您的帮助。
有一种方法可以从 HttpContextBase 获取角色数组吗?
我正在寻找这样的课程:
public static IList<string> GetUserRoles(this HttpContextBase context)
{
if (context != null)
{
}
// return roles array;
}
谢谢您的帮助。
您可以使用:
System.Web.Security.Roles.GetAllRoles()
您为什么要使用 HttpContextBase?
* 编辑 * 哎呀,我现在看到您想要给定用户的角色列表。我以为你想要所有可用角色的列表。
您可以遍历角色并检查哪些角色适用:
HttpContextBase.User.IsInRole(role);
可能您在 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;
}