将角色动态映射到 ASP.Net MVC 中的控制器 [英] dynamically mapping roles to controllers in ASP.Net MVC

查看:16
本文介绍了将角色动态映射到 ASP.Net MVC 中的控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在我的 MVC 应用程序中对过滤器中的授权角色进行硬编码,如下所示:

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?

推荐答案

您将需要编写自己的授权过滤器(可能通过扩展内置过滤器).

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.

您不需要弄乱 MVC 源代码 - 您只需要创建一个从 System.Web.Mvc.AuthrorizeAttribute 继承的类,覆盖 AuthorizeCore,然后使用您的属性代替默认值:

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:

public class CustomAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Put your custom logic here, returning true for success and false for failure,
        // or return base.AuthorizeCore(httpContext) to defer to the base implementation
    }
}

这篇关于将角色动态映射到 ASP.Net MVC 中的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆