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

后端 未结 2 1615
情书的邮戳
情书的邮戳 2020-12-23 16:57

I want to check some things about the state of the session, the user agent, etc, and possibly take action and return a special view BEFORE a controller method gets a chance

相关标签:
2条回答
  • 2020-12-23 17:28

    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.

    0 讨论(0)
  • 2020-12-23 17:28

    One way you can do this is to redirect to a different ActionMethod to show the view. Code example is in this discussion:

    Redirecting to specified controller and action in asp.net mvc action filter

    0 讨论(0)
提交回复
热议问题