基于角色的模型列表授权

Shr*_*r S 6 authorization role-based authorize-attribute asp.net-mvc-3

我有3个型号[用户,角色和用户角色]

Use {ID [PK], Name, Email, Password, .....}
Role {ID [PK], Name, Description, .......}
UserRole {UserID [FK], RoleID [FK]}

考虑使用[Authorize]属性在控制器上进行基于角色的授权,指定用户必须具有管理员角色才能访问类中的任何控制器操作

[Authorize(Roles = "Administrator")]
public class PageController : Controller
{
    // Controller code here
}
Run Code Online (Sandbox Code Playgroud)

这很好,我需要的是,

有没有办法将我的角色集分配给[授权]属性?例如

我将从登录用户中获取已分配的角色并将其存储在列表中.是否可以将此列表分配给[授权]属性?如下所示:

[Authorize(Roles = MyDynamicallyLoadedList)]
public class PageController : Controller
{
    // Controller code here
}
Run Code Online (Sandbox Code Playgroud)

Rap*_*aus 1

嗯,有两个问题。

首先,您不能使用列表作为属性的参数。您可以使用数组代替。 http://msdn.microsoft.com/fr-fr/library/ms177221%28v=vs.100%29.aspx

其次,属性参数的值必须在编译时已知:列表的内容只有在运行时才知道。

您会收到如下消息:

属性参数必须是属性参数类型的常量表达式、typeof 表达式或数组创建表达式

解决方案是创建一个新的 Authorization 属性(继承自AuthorizeAttribute),并覆盖AuthorizedCore

可以在这里找到一个示例(您可以适应您的问题)