ASP.NET MVC event that happens just before action is called?
I want to set the value of Thread.CurrentCultu开发者_开发问答re
based on some route data, but I can't find an event to hook to that fires after the routes are calculated and before the action method is called.
Any ideas?
You could write a custom 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 could decorate your base controller with this custom attribute. And here's a blog post illustrating a sample implementation of such filter.
If you want to apply the culture on every action, you could create a base controller and override the OnActionExecuting
method.
If you want to add the filter to all controllers, not just select ones, you can add it to the "global filters". You do this in Application_Start()
in your 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);
}
精彩评论