Sitecore10 MVC中AuthorizationFilterAttribute的OnAuthorization方法未触发
自定义授权过滤器代码如下:
public class AuthenticationRequiredAttribute : System.Web.Http.Filters.AuthorizationFilterAttribute { public override bool AllowMultiple { get { return false; } } public override void OnAuthorization(HttpActionContext actionContext) { base.OnAuthorization(actionContext); } }
已将该属性标记在控制器上:
[AuthenticationRequired] public class ProfileController : BaseController { public ProfileController(IMyRepository repository) : base(repository) { } }
但AuthenticationRequired过滤器始终未触发,请问遗漏了什么?
检查控制器基类类型
你使用的System.Web.Http.Filters.AuthorizationFilterAttribute是ASP.NET Web API专属过滤器,仅对继承自System.Web.Http.ApiController的控制器生效。如果BaseController继承的是MVC的System.Web.Mvc.Controller,该过滤器不会触发,需改用System.Web.Mvc.AuthorizationFilterAttribute实现自定义过滤器。添加调试验证逻辑
当前过滤器的OnAuthorization方法仅调用基类方法,无自定义输出,可能误判了触发状态。可添加调试代码确认执行情况:public override void OnAuthorization(HttpActionContext actionContext) { System.Diagnostics.Debug.WriteLine("AuthenticationRequiredAttribute 已执行"); base.OnAuthorization(actionContext); }启动调试后查看输出窗口,或直接在方法内打断点验证。
确认路由匹配正确性
如果请求URL未匹配到ProfileController的路由规则,过滤器自然不会触发。检查WebApiConfig中的路由配置,确保请求路径能正确映射到该控制器的方法。排查过滤器执行顺序冲突
若控制器或全局注册了其他授权过滤器(如原生[Authorize]),需确认执行顺序是否导致当前过滤器被跳过。可通过调试断点跟踪过滤器执行流程,或调整特性标记的顺序。检查依赖注入配置
若控制器通过依赖注入容器实例化,确认容器是否正确识别并应用控制器上的过滤器特性。部分DI容器需要额外配置才能支持过滤器的特性注入。
内容的提问来源于stack exchange,提问作者Himanshu Agarwal

