I have a permissions attribute which takes a list of enum values for roles:
[CheckRoles(SystemRole.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;
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:Hope this helps.