Reputation: 6851
There is a way to get the array of role from the HttpContextBase ?
I'm looking to do a class like that:
public static IList<string> GetUserRoles(this HttpContextBase context)
{
if (context != null)
{
}
// return roles array;
}
Thanks for the help.
Upvotes: 1
Views: 1685
Reputation: 9431
You can use:
System.Web.Security.Roles.GetAllRoles()
For what reason do you want to use HttpContextBase?
* EDIT * Oops, I see now you want the list of roles for a given user. I thought you wanted the list of all available roles.
you could loop through the roles and check which ones apply:
HttpContextBase.User.IsInRole(role);
Upvotes: 3
Reputation: 35597
Probably you're using a GenericPrincipal in the Application_AuthenticateRequest. I would suggest you to create a custom principal which exposes an array of roles:
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);
}
}
now you can read your cookie and create a custom principal.
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;
}
}
and your function would look something like this:
public static IList<string> GetUserRoles(this HttpContextBase context)
{
if (context != null)
{
return(((CustomPrincipal)context.User).Roles);
}
return (null);
// return roles array;
}
Upvotes: 2