An ASP.NET MVC event that occurs immediately before a call?

I want to set a value Thread.CurrentCulturebased on some route data, but I cannot find an event to connect to what fires after calculating the routes and before calling the action method.

Any ideas?

+5
source share
3 answers

You can write your own action filter attribute :

public class CustomFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // This method is executed before calling the action
        // and here you have access to the route data:
        var foo = filterContext.RouteData.Values["foo"];
        // TODO: use the foo route value to perform some action

        base.OnActionExecuting(filterContext);
    }
}

And then you can decorate your base controller with this custom attribute. And here 's a blog post illustrating an example implementation of such a filter.

+15
source

, OnActionExecuting.

+4

If you want to add a filter to all controllers, and not just select them, you can add it to the "global filters". You do this in the Application_Start()Global.asax.cs file:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    // Register global filter
    GlobalFilters.Filters.Add(new CustomFilterAttribute ()); // ADDED

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}
+1
source

All Articles