Reputation: 8657
Basically I'm writing my own version of a 'RoleProvider' and 'AuthorizeAttribute'. I've got an Enum (as a bit field) with a list of all possible roles:
namespace myProject.Global
{
[Flags]
enum Roles
{
Viewer = 1,
User = 2,
Admin = 4,
Superadmin = 8
}
}
My AuthorizeAttribute works similarly to the existing one. In my logic, I loop through each 'Authorized' role and check to see if the user belongs to it. _rolesSplit is an array of the roles provided in the AuthorizeAttribute for a particular action. httpContext.Session["Roles"] is an integer representing the user's roles.
foreach (string roleName in _rolesSplit)
{
if ((httpContext.Session["Roles"] & myProject.Global.Roles[roleName]) == myProject.Global.Roles[roleName]) return true;
}
return false;
This is the part I can't get working: APICText.Global.Roles[roleName]. I'm new to .NET development so I'm not sure how to make this work. I basically need to pass something the role name and get the associated value back. How do I do this?
Upvotes: 1
Views: 388
Reputation: 41588
What you need is Enum.Parse.
Try something like this...
foreach (string roleName in _rolesSplit)
{
if (httpContext.Session["Roles"] & (Roles)Enum.Parse(typeof(Roles), roleName) == (Roles)Enum.Parse(typeof(Roles), roleName)) return true;
}
or this...
foreach (string roleName in _rolesSplit)
{
Roles role = (Roles)Enum.Parse(typeof(Roles), roleName);
if (httpContext.Session["Roles"] & role == role) return true;
}
Upvotes: 3