Asp – MVC data annotation layer: where to put the set CurrentUICulture statement

asp.net-mvcdata-annotationslocalization

I am getting crazy with the localization of an MVC application.

After a recent question of mine I have followed this approach:

  1. The language is stored in Session["lang"]
  2. Each controller inherits from my own BaseController, which overrides OnActionExecuting, and in this method reads the Session and sets CurrentCulture and CurrentUICulture

This works great, until the Data Annotation Layer comes in. It seems like it gets called BEFORE the action itself is executed, and therefore it always gets the error messages in the default language!

The fields declarations go like this:

[Required(ErrorMessageResourceName = "validazioneRichiesto", ErrorMessageResourceType = typeof(Resources.Resources))]
public string nome { get; set; }

So, is there any reasonable place where I can put the call?

I initialize the Data Annotation Model Binder in my Controller constructor.

public CardController() : base() {
    ModelBinders.Binders.DefaultBinder =
    new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();
}

So, since Session is always null in the controller's constructor, and the action override is called AFTER the data annotation has validated the fields, where can I possibly set the CurrentCulture and CurrentUICulture to get localized errors?

I tried putting the CurrentCulture and CurrentUiCulture in Application_* (e.g. Application_AcquireRequestState or Application_PreRequestHandlerExecute) seems to have no effect…

Best Answer

As the culture is a global user setting, I am using it in the global.asax.cs file in the Application_BeginRequest method.

It does the work for me (using cookies) but the Session is also available there.

EDIT:

/by Brock Allen: http://www.velocityreviews.com/forums/t282576-aspnet-20-session-availability-in-globalasax.html/

Session is available in PreRequesthandlerExecute.

The problem is that your code is being executed for every request into the server, and some requests (like ones for WebResourxe.axd) don't utlilize Session (because the handler doesn't implement IRequireSessionState). So change your code to only access Session if that request has access to it.

Change your code to do this:

protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
    if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
        SetCulture();    
}

Anyway, not sure if it works with mvc

Related Topic