What gets the instance first in ASP.NET MVC, Action Filters or Controllers?

Are MVC action filter attributes executed before the controller instance is created? I have a controller property that I would like to test from ActionFilter. Is it possible?

+4
source share
3 answers

According to Professional ASP.NET MVC 1.0, ActionFilters run after the controller instance is created. By the time OnActionExecuting (the first method called by ActionFilter), the controller context is available.

+4
source

The controller will receive an instance before the Action Filter OnActionExecuted and OnActionExecuting events are triggered. You can also access the controller through the filterContext parameter, which is passed to 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 } 
+2
source

The abstract class System.Web.Mvc.ActionFilterAttribute (get your own ActionFilter from this class) has 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 } 
+1
source

All Articles