是否保证调用ActionFilterAttribute的所有阶段?

spe*_*der 6 c# asp.net-mvc actionfilterattribute asp.net-mvc-5

在写这个答案时,我被问到是否有关于ActionFilterAttribute行为的保证.我无法自信地回答.

特别是,方法四个OnActionExecuted,OnActionExecuting,OnResultExecutedOnResultExecuting保证被要求穿过属性,还是有情节的所有请求(例如异常,断开的连接等),其中一个或多个阶段可能不火呢?

Dis*_*ile 2

不,不保证他们会被调用。

想想授权过滤器。如果授权失败,您是否希望运行任何操作过滤器?这可能是一个很大的安全漏洞。我相信异常也会停止过滤器的管道,并且只有异常过滤器将从该点执行。

给定以下过滤器:

public class ExampleFilterAttribute : FilterAttribute, IActionFilter
{
    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        // this code is never reached...
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

关于以下控制器操作:

[ExampleFilter]
public ActionResult Index()
{
    // this code is never reached...
    return View();
}
Run Code Online (Sandbox Code Playgroud)

由于存在异常,因此该Index()方法或该方法OnActionExecuted()都未到达。OnActionExecuting()