Jason Wicker
Jason Wicker

Reputation: 3456

Which gets instantiated first in ASP.NET MVC, Action Filters or Controllers?

Do the MVC Action Filter Attributes run, before the controller is instantiated? I have a property of the controller, that I would like to check from the ActionFilter. Is this possible?

Upvotes: 4

Views: 1498

Answers (3)

eu-ge-ne
eu-ge-ne

Reputation: 28153

Abstract class System.Web.Mvc.ActionFilterAttribute (derive your own ActionFilter from this class) have 4 OnXXX methods:

  • OnActionExecuting
  • OnActionExecuted
  • OnResultExecuting
  • OnResultExecuted

I think in OnActionExecuting you can check your controller:

YourController controller = filterContext.Controller as YourController
if(controller != null)
{
    // check your controller
}

Upvotes: 1

Chris Pietschmann
Chris Pietschmann

Reputation: 29895

The Controller will get instantiated before the Action Filter's OnActionExecuted and OnActionExecuting events are fired. Also you can access the Controller through the "filterContext" parameter that's passed to the event handlers.

public class TestActionAttribute : FilterAttribute, IActionFilter
{
    #region IActionFilter Members

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var controller = filterContext.Controller;
    }

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var controller = filterContext.Controller;
    }

    #endregion
}

Upvotes: 2

Ender
Ender

Reputation: 15221

According to the Professional ASP.NET MVC 1.0 book, ActionFilters run after the controller is instantiated. By the time of OnActionExecuting (the first method called by an ActionFilter), the Controller context is available.

Upvotes: 4

Related Questions