I have a permissions attribute which takes a list of enum values for roles:
[CheckRoles(S开发者_开发百科ystemRole.ID.Admin, SystemRole.ID.User)]
public class MyController : Controller
{
....
}
However, in other parts of the code I would like to check if the user is in any of these roles, so I can go to the correct page. So the code looks something like:
if (roles.IsInAnyRoles(user, SystemRole.ID.Admin, SystemRole.ID.User)
{
... Do something in MyController ...
}
You can see the repetition here. I really want to have the two roles in a variable or initialiser list or something, that I can pass to both the Attribute and the method. Creating a const array doesn't work. Is there a way of doing this? Can I store the array initialiser somehow?
Any help would be greatly appreciated!
UPDATE
I have made the roles enum int a Flags enum (and given the items appropriate values). This means I can or the values together to give a single, constant value. I can now use that constant value in the Attribute, and in methods. Thanks to Danny Chen below.
In my real project experiences, I'd like to define roles like this;
[Flags]
public enum Role
{
Staff = 0,
Supervisor = 1,
Manager = 2,
Admin = 4,
HelpDesk = 8
}
The reason is that one account often has a few roles associated, e.g. someone is a supervisor of Bob, also he is the manager of IT department. In this case his role is Role.Supervisor | Role.Manager
, so that he could use all functions provided to Role.Supervisor (such as approving Bob's leaving request), meanwhile he can approve leaving requests from all IT department staff. The action looks like:
[CheckRole(Role.Supervisor, Role.Manager)]
public ActionResult ApproveLeavingRequest()
{
//the roles in the constructor of CheckRoleAttribute are OR related
}
[CheckRole(Role.Manager|Role.Supervisor, Role.Admin)]
public ActionRequest ModifySystemSettings()
{
//this method is provided to a small group of people
//those who is a manager and a supervisor
//or he is an admin
}
[CheckRole(Role.Manager|Role.Supervisor|Role.Admin)]
//maybe we need to add Role.Boss into the system :)
public ActionRequest IncreasePay()
{
//only the boss account can invoke this method
}
Hope this helps.
精彩评论