Are all phases of an ActionFilterAttribute guaranteed to be called?

喜你入骨 提交于 2019-12-07 02:16:04

问题


In writing this answer, I was asked if there are guarantees about the behaviour of the ActionFilterAttribute. and I was unable to answer with confidence.

In particular, are all four of the methods OnActionExecuted, OnActionExecuting, OnResultExecuted & OnResultExecuting guaranteed to be called for all requests that pass through the attribute, or are there circumstances (such as exceptions, dropped connection etc) where one or more of the phases might not fire?


回答1:


No they are not guaranteed to be called.

Think of the Authorization filters. If authorization fails, would you expect any action filters to run? That could be a big security hole. I believe an exception would also stop the pipeline of filters and only exception filters would be executed from that point.

Given the following filter:

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

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        throw new NotImplementedException();
    }
}

on the following controller action:

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

Neither the Index() method or the OnActionExecuted() is ever reached because OnActionExecuting() has an exception.



来源:https://stackoverflow.com/questions/24333831/are-all-phases-of-an-actionfilterattribute-guaranteed-to-be-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!