ASP.NET MVC event that happens just before action is called?

前端 未结 3 1234
既然无缘
既然无缘 2021-02-06 12:23

I want to set the value of Thread.CurrentCulture based on some route data, but I can\'t find an event to hook to that fires after the routes are calculated and befo

相关标签:
3条回答
  • 2021-02-06 13:00

    If you want to apply the culture on every action, you could create a base controller and override the OnActionExecuting method.

    0 讨论(0)
  • 2021-02-06 13:17

    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.

    0 讨论(0)
  • 2021-02-06 13:18

    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);
    }
    
    0 讨论(0)
提交回复
热议问题