覆盖授权属性在ASP.NET MVC属性、ASP、MVC、NET

2023-09-02 20:41:57 作者:我一架尸身罷了°

我对我施加的授权属性,因为我想几乎所有的控制器(和他们的行动沿),被授权的MVC控制器基类。

I have an MVC controller base class on which I applied the Authorize attribute since I want almost all of the controllers (and their actions along) to be authorized.

不过,我需要有一个控制器和其他控制器未经授权的行动。我希望能够与 [授权(假)] 或东西,但无法满足这一要求。

However I need to have a controller and an action of another controller unauthorized. I wanted to be able to decorate them with the [Authorize(false)] or something but this is not available.

任何想法?

推荐答案

编辑:既然ASP.NET MVC 4,最好的办法就是使用内置的使用AllowAnonymous 属性。

Since ASP.NET MVC 4 the best approach is simply to use the built-in AllowAnonymous attribute.

答案下面是指早期版本的ASP.NET MVC

The answer below refers to earlier versions of ASP.NET MVC

您可以创建一个自定义的授权属性从标准AuthorizeAttribute继承一个可选的布尔参数指定授权是否需要与否。

You could create a custom authorisation attribute inheriting from the standard AuthorizeAttribute with an optional bool parameter to specify whether authorisation is required or not.

public class OptionalAuthorizeAttribute : AuthorizeAttribute
{
    private readonly bool _authorize;

    public OptionalAuthorizeAttribute()
    {
        _authorize = true;
    }

    public OptionalAuthorizeAttribute(bool authorize)
    {
        _authorize = authorize;
    }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if(!_authorize)
            return true;

                    return base.AuthorizeCore(httpContext);
    }
}

然后你可以装饰与属性的基本控制器:

Then you can decorate your base controller with that attribute:

[OptionalAuthorize]
public class ControllerBase : Controller
{
}

和任何控制器,你不想授权干脆用替代与假 - 例如

and for any controllers you don't want authorisation simply use the override with a 'false' - e.g.

[OptionalAuthorize(false)]
public class TestController : ControllerBase
{
    public ActionResult Index()
    {
        return View();
    }
}