一个角色的共享初始化属性和方法之间的属性 [英] Sharing initialisation of a roles attribute between the attribute and methods
问题描述
我有一个权限属性,该属性花费的角色枚举值的列表:
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
{
....
}
不过,在code的其他部分,我想检查,如果用户在这些角色,这样我就可以去到正确的页面。因此,code看起来是这样的:
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?
任何帮助将大大AP preciated!
Any help would be greatly appreciated!
更新
我所作出的角色枚举int类型的标志枚举(并给予适当的项目值)。这意味着我可以或值加在一起给一个单一的,恒定值。
我现在可以使用恒定的值在属性,并在方法。
由于下面丹尼臣。
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
}
的原因是,一个帐户往往有几个角色关联,例如有人是Bob的主管,也是他就是IT部门的经理。在这种情况下,他的作用是 Role.Supervisor | Role.Manager
,这样他就可以使用提供Role.Supervisor所有功能(如批准鲍勃的离开要求),同时他可以批准离开所有IT部门人员的请求。操作如下:
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
}
希望这有助于。
这篇关于一个角色的共享初始化属性和方法之间的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!