自定义 AuthorizeAttribute 被调用太多次

Sat*_*i K 5 c# asp.net authorization asp.net-web-api

我目前正在开发一些安全措施来保护网络服务调用。我决定扩展授权属性并覆盖 isAuthorized 函数以及 ActionFilterAttribute OnActionExecuted。但是,当我调试程序时,我注意到如果我要在该类中的 api 函数上添加 [Authorize(Roles = "Read")] 类级别和 [Authorize(Roles = "Admin")],则 isAuthorized总共被调用了 3 次。这可能不是什么大问题,但由于在我的 isAuthorized 中,我正在数据库中创建和验证令牌。如果我能够消除这个多余的过程并且每次服务调用只调用一次 isAuthorized ,那将是理想的。

  public class CustomuAuthorizeAttribute : AuthorizeAttribute
{

    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        bool allowedAccess = true;
        ... logic

    }
   }
Run Code Online (Sandbox Code Playgroud)

覆盖执行的 OnAction。即使 isAuthorized 被命中 3 次,这实际上也只会被命中一次。

    public class CustomAuthorizeFilter : ActionFilterAttribute
{

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
     .. logic
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑 我发现将 [AttributeUsage(AttributeTargets.Method| AttributeTargets.Class)] 添加到 authorizeattribute calss 解决了被多次调用的问题