ASP.NET MVC localization using ActionFilter

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 excuted, 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.


2 thoughts on “ASP.NET MVC localization using ActionFilter

  1. Or you can override Execute method in Controller class, to set CurrentCulture property.

    public abstract class ControllerBase : Controller

    protected override void Execute(System.Web.Routing.RequestContext requestContext)
    Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(“en”);

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s