【问题标题】:Can I access my controller/action/verb from my derived AuthorizeAttribute?我可以从派生的 AuthorizeAttribute 访问我的控制器/动作/动词吗?
【发布时间】:2009-11-19 02:59:01
【问题描述】:

作为一个理论练习,帮助我了解与 MVC 相关的成员模型的来龙去脉,我想弄清楚我是否可以从外部资源加载权限,为了我的原型,我有一个平面具有如下列表的文件:

Controller1,Method1,Get,Anonymous
Controller1,Method1,Post,User,Administrator
Controller2,Method1,Get,Administrator
Controller2,Method1,Post,Administrator
Controller2,Method2,Get,User,Editor,Administrator
Controller2,Method2,Post,Editor,Administrator

我可以使用正则表达式对其进行解析,从而为我提供对每个控制器/动作/动词组合具有权限的角色列表。

我有我的控制器操作:

[CustomAuthorize]
public ActionResult Index()
{
    /* Do stuff */
}

我也有我的自定义授权组件:

public class CustomAuthorize : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        /* How do I access which Controller/Action/Verb fired this? */
    }
}

为了能够即时确定哪些角色有权访问此控制器/动作/动词,我需要能够确定哪个控制器/动作/动词调用了 CustomAuthorize 属性。

我知道我可以像这样向我的类添加属性:

public class CustomAuthorize : AuthorizeAttribute
{
    public string Controller { get; set; }
    public string Action { get; set; }
    public string Verb { get; set; }
}

然后使用以下方法调用我的属性:

[CustomAuthorize(Controller="Home",Action="Index",Verb="Get")]
public ActionResult Index()
{
}

但这似乎是一个令人头疼的维护问题。如果我可以使用 [Authorize] 并让我的 CustomAuthorize.AuthorizeCore 方法确定哪个控制器/动作/动词从 AuthorizeCore 方法中引用它,那就太好了。

这可能吗?如果是这样,有人可以指出我将如何实现这一目标的正确信息方向吗?

【问题讨论】:

    标签: c# .net asp.net-mvc


    【解决方案1】:

    您可能希望查看重写 OnAuthorization。它获取一个 AuthorizationContext 参数,该参数具有对 Controller 和 RouteData 的引用。不过,请看一下标准 AuthorizeAttribute 的作用,尤其是在缓存方面。你可能会在我写在我的blog 上的一篇关于customizing authorization in MVC 的文章中找到一些想法。

    【讨论】:

    • 我已阅读您关于自定义授权的帖子。内容丰富。看起来你的建议应该可以解决问题。
    【解决方案2】:

    尝试覆盖 OnAuthorization。

    public class TestAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            string controllerName = filterContext.RouteData["controller"];
            string actionName = filterContext.RouteData["action"];
            string verb = filterContext.HttpContext.Request.HttpMethod;
    
            // .. do your processing
            // if fail...
            filterContext.Result = new HttpUnauthorizedResult();
    
            base.OnAuthorization(filterContext);
        }
    }
    

    【讨论】:

    • 如果没有上面提到的关于缓存的警告,这有点危险。
    • 很遗憾我不能同时接受这两个答案......它们既有用又能提供信息,并且都可以满足我的需求。
    • @Craig - 作为一个理论练习,这给出了我所追求的信息,该方法的前 3 行就是我所追求的。正如电视的回答所暗示的那样,我可以在我的 AuthorizeCore() 方法中处理其余部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 2013-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-18
    相关资源
    最近更新 更多