3

Is it possible to make an action filter or something that runs before the action method itself runs on the controller?

I need this to analyze a few values in the request before the action runs.

Mathias Lykkegaard Lorenzen
  • 15,031
  • 23
  • 100
  • 187

3 Answers3

13

You can override OnActionExecuting method in controller class

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
        base.OnActionExecuting(filterContext);
//Your logic is here...
}
Ivan Manzhos
  • 743
  • 6
  • 12
5

You could use an attribute:

public class MyFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Your logic here...

        base.OnActionExecuting(filterContext);
    }
}

And if you want to apply it to all controllers, in your Global.asax.cs:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new MyFilterAttribute());
}

protected void Application_Start()
{
    // Other code removed for clarity of this example...

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    // Other code removed for clarity of this example...
}
Adrian Thompson Phillips
  • 6,893
  • 6
  • 38
  • 69
0

If u don't want to use a base controller u can also add a own HttpHandler and register it in the web.config. In the BeginProcessRequest method u can analyse the values.

rfcdejong
  • 2,219
  • 1
  • 25
  • 51