在 ASP.Net MVC 中动态地将角色映射到控制器
我目前正在 MVC 应用程序的过滤器中对授权角色进行硬编码,如下所示:
[Authorize(Roles = "Administrator,Manager")]
我希望最终有一种方法将角色映射到每个控制器,以便站点管理员可以处理分配哪些角色可以执行每组操作行动。
string roles = DoSomethingToGetAllowableRoles(controllerName);
[Authorize(Roles = roles)]
我想象我需要一个数据库表来以某种方式保存每个控制器的列表,然后另一个表将控制器映射到角色。我想要的是一个页面,我可以在其中列出每个控制器,然后有一组复选框列出适用于该控制器的每个角色。
任何人都有一个例子或者可以引导我朝实现这一目标的方向前进吗?
I am currently hard coding the authorized roles in the filter in my MVC applications like so:
[Authorize(Roles = "Administrator,Manager")]
I'd like to eventually have a way to map the roles to each controller, so that the site admin can handle assigning what roles can perform each set of actions.
string roles = DoSomethingToGetAllowableRoles(controllerName);
[Authorize(Roles = roles)]
I'm imagining that I need to have a database table that somehow keeps a listing of each controller, and then another table mapping the controllers to the roles. What I'd like is a page where I can list out each controller and then have a set of check boxes that lists each role that applies to that controller.
Anyone have an example or can lead me in a direction that will accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将需要编写自己的授权过滤器(可能通过扩展内置过滤器)。
原因是您无法像这样动态分配属性参数。
您不需要弄乱 MVC 源代码 - 您只需创建一个继承自 System.Web.Mvc.AuthrorizeAttribute 的类,覆盖 AuthorizeCore,然后使用您的属性代替默认属性:
You're going to need to write your own authorization filter (probably by extending the built in one).
The reason for this is that you can't assign attribute parameters dynamically like that.
You won't need to mess with the MVC source code - you just need to create a class which inherits from System.Web.Mvc.AuthrorizeAttribute, override AuthorizeCore, and then use your attribute in place of the default: