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

查看:175
本文介绍了在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源$ C ​​$ C - 你只需要创建一个从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天全站免登陆