本文介绍了您可以启用[授权]的控制器,但禁用它一个行动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 [授权] 为每一个动作在我的管理控制器除了登录的行动。

  [授权(角色=管理员)]
公共类AdminController:控制器
{
    //我可以在这里举行禁用授权?
    公众的ActionResult登录()
    {
        返回查看();
    }
}


解决方案

我不认为你可以用标准的授权属性做到这一点,但你可以得到从AuthorizeAttribute自己的属性,它利用一个动作列表,允许和允许访问只是那些动作。你可以看一下源为AuthorizeAttribute在关于如何做到这一点的想法。如果你做到了,它可能是这样的:

  [AdminAuthorize(角色=管理员,豁免=登录,注销)
公共类AdminController:控制器
{
    公众的ActionResult登录()
    {
        返回查看();
    }    公众的ActionResult登录()
    {
        返回查看();
    }    ...等,限制行动...
}

修改:仅供参考,最终我对面有必要做同样的事情对我自己跑了,我走了不同的方向。我创建了一个默认的授权过滤器提供商和应用的全球授权过滤器。授权滤波器提供商使用反射来检查是否一个动作或控制器具有特定授权属性施加,如果是这样,委托给它。否则,应用默认的授权过滤器。这再加上AuthorizeAttribute允许公众访问得出的PublicAttribute。现在,我得到默认的安全访问,但可以通过授予公共接入[公用] 应用到操作或者控制器。更具体授权也可以在必要时使用。见我的博客<一href=\"http://farm-fresh-$c$c.blogspot.com/2011/04/default-authorization-filter-provider.html\">http://farm-fresh-$c$c.blogspot.com/2011/04/default-authorization-filter-provider.html

I would like to use [Authorize] for every action in my admin controller except the Login action.

[Authorize (Roles = "Administrator")]
public class AdminController : Controller
{
    // what can I place here to disable authorize?
    public ActionResult Login()
    {
        return View();
    }
}
解决方案

I don't think you can do this with the standard Authorize attribute, but you could derive your own attribute from AuthorizeAttribute that takes a list of actions to allow and allows access to just those actions. You can look at the source for the AuthorizeAttribute at www.codeplex.com for ideas on how to do this. If you did, it might look like:

[AdminAuthorize (Roles = "Administrator", Exempt = "Login, Logout") ]
public class AdminController : Controller
{
    public ActionResult Login()
    {
        return View();
    }

    public ActionResult Login()
    {
        return View();
    }

    ... other, restricted actions ...
}

EDIT: FYI, I eventually ran across a need to do something similar on my own and I went a different direction. I created a default authorization filter provider and apply a global authorize filter. The authorization filter provider uses reflection to check if an action or controller has a specific authorize attribute applied and, if so, defers to it. Otherwise, it applies a default authorization filter. This is coupled with a PublicAttribute derived from AuthorizeAttribute that allows public access. Now, I get default secured access, but can grant public access via [Public] applied to an action or controller. More specific authorization can also be applied as necessary. See my blog at http://farm-fresh-code.blogspot.com/2011/04/default-authorization-filter-provider.html

这篇关于您可以启用[授权]的控制器,但禁用它一个行动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 03:02