I have a custom AuthorizeAttribute
in a legacy MVC5 project:
public class AuthorizeWithLoggingAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!base.AuthorizeCore(httpContext)) {Log(FilterContext);}
}
}
We noticed while looking through the logs, that in addition to being to applied to controllers with [AuthorizeWithLogging]
, it was being called explicitly elsewhere in the code, generating spurious logs:
var filters = new FilterInfo(FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor));
foreach (var authFilter in filters.AuthorizationFilters)
{
authFilter.OnAuthorization(authContext);
if (authContext.Result != null) {return false;}
}
Is there a way to tell (via StackTrace
or something) whether the OnAuthorization
method is being explicitly called, or called from the attribute? The best I currently have is
Environment.StackTrace.Contains("at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters")
.