【问题标题】:Are all phases of an ActionFilterAttribute guaranteed to be called?是否保证调用 ActionFilterAttribute 的所有阶段?
【发布时间】:2014-06-20 18:52:06
【问题描述】:
在写this answer 时,有人问我是否对ActionFilterAttribute 的行为有保证。我无法自信地回答。
特别是OnActionExecuted、OnActionExecuting、OnResultExecuted&OnResultExecuting这四个方法是否保证所有通过该属性的请求都会被调用,或者是否存在情况(如异常,丢弃连接等)其中一个或多个阶段可能不会触发?
【问题讨论】:
标签:
c#
asp.net-mvc
asp.net-mvc-5
actionfilterattribute
【解决方案1】:
不,它们不能保证被调用。
想想授权过滤器。如果授权失败,您是否希望运行任何操作过滤器?这可能是一个很大的安全漏洞。我相信异常也会停止过滤器的管道,并且只会从那时开始执行异常过滤器。
给定以下过滤器:
public class ExampleFilterAttribute : FilterAttribute, IActionFilter
{
public void OnActionExecuted(ActionExecutedContext filterContext)
{
// this code is never reached...
}
public void OnActionExecuting(ActionExecutingContext filterContext)
{
throw new NotImplementedException();
}
}
关于以下控制器操作:
[ExampleFilter]
public ActionResult Index()
{
// this code is never reached...
return View();
}
Index() 方法或 OnActionExecuted() 都无法到达,因为 OnActionExecuting() 有一个异常。