如何在自定义AuthorizeAttribute中允许[Authorize]

Fab*_*cio 2 c# asp.net-web-api

我有这样的自定义AuthorizeAttribute

public class DevMode : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (myConditionToAuthorize)
        {
            // how to allow [Authorize] ?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是它与[Authorize]标签一起使用,如下所示:

[Authorize, DevMode]
public class UserController : ApiController { ... }
Run Code Online (Sandbox Code Playgroud)

我需要让[Authorize] == true内心[DevMode]

或者最好将它们放在一个独特的授权类中?但后来我不知道检查授权数据.

Dar*_*rov 5

或者最好将它们放在一个独特的授权类中?

哦,是的,那确实会更好.您可以简单地从中派生AuthorizeAttribute并调用基本方法:

public class DevModeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var authorize = base.IsAuthorized(actionContext);
        if (!authorized)
        {
            // the user is not authorized, no need to go any further
            return false;
        }

        // now apply your custom authorization logic here and return true or false
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

[DevMode]
public class UserController : ApiController { ... }
Run Code Online (Sandbox Code Playgroud)

  • `System.Web.Mvc.AuthorizeAttribute` 和 `System.Web.Http.AuthorizeAttribute` 之间存在巨大差异。我希望您使用后者,因为第一个显然没有在 API 控制器中调用。另外,如果您使用 ASP.NET Web API,为什么您的问题标记器使用“asp.net-mvc”而不是使用“asp.net-web-api”标记?我将对其进行更新,以解决这两种技术之间可能使读者感到困惑的误解。 (2认同)