How do I get certain code to execute before every single controller action in ASP.NET MVC 2?

All depends what exactly you want to do, and how. Three options below:


You can use route constraints for this. They are executed when evaluating the route to match to.

routes.MapRoute(
    "HomeWithConstraint",
    "Home/{action}",
    new {controller="Home", action="index"},
    new { x = new MyCustomRouteConstraint () }
);

// without constraint, i.e. if above didnt pass
routes.MapRoute(
    "HomeWithConstraint",
    "Home/{action}",
    new {controller="Home", action="index"}
);

The MyCustomRouteConstraint type above would check for x==0 etc in your example. Not sure exactly what you want to do, but this will allow you to check conditions before running and set additional route values etc.

See here for example of custom route constraints.


Alternativly, yes you can use a custom ActionFilter, just apply it to the controller class, and it will be called before any action is executed. Something like:

public class CheckXActionFilterAttribute : ActionFilterAttribute
{

      public override void OnActionExecuting(ActionExecutingContext filterContext)
      {
           if(x == 0)
           {
               // do something
               // e.g. Set ActionParameters etc
           }
           else
           {
               // do something else
           }
      }


}

Another option is to have all you controllers (or the relevant ones) inherit from a custom controller you make, and override :

OnActionExecuting

See here for details.

To do the same as the filter, or routing constraints.

Leave a Comment