Are all phases of an ActionFilterAttribute guaranteed to be called?
Asked Answered
N

1

6

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?

Noam answered 20/6, 2014 at 18:52 Comment(0)
B
2

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.

Boulevard answered 20/6, 2014 at 19:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.