Action filters in ASP.NET MVC provide a great way to apply custom behavior to selected controller actions. They let you execute code before or after the actual action has been executed. That reminds of Aspect Oriented Programming and can be used to apply cross cutting concerns to controllers.
One of the things that first seemed reasonable to apply using action filters was localization. An action filter that sets current thread’s culture before an action is invoked might look like this:
public class LocalizationCacheFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en");
}
}
When you apply this action filter to your actions, the culture is set before the action, causing any code that is run later, including the action, to use the given culture. Easy and nice, however, there’s a small problem.
It seems that model binding happens before action filters are executed, so that means that model binder will have no idea about a custom culture. That means that any validation that will be made on the model will produce validation error messages for the default culture, not the one you will set in the action filter. JavaScript validation will, however, produce the correct localized error messages, because JavaScript error messages are created at view’s render time and embedded in the output HTML. At that time, the action filter has already have been executed.
This issue caused me some head-scratching. The fix is to set custom culture earlier, in HttpApplication
‘s BeginRequest
event handler, for example.
CodeProject