Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: When to set Thread.CurrentThread.CurrentUICulture?

I am just beginning to localize an ASP.NET MVC application. Most of the strings will be defined in resource files and retrieved via Matt's Localization Helpers. Other strings must be stored in a database.

My Question: Should I set CurrentUICulture early in the request pipeline and use that throughout the application, or directly use Request.UserLanguages[0] whenever needed?

Right now I'm thinking that I should set CurrentUICulture in Application_BeginRequest. The implementation would look something like this:

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var cultureName = HttpContext.Current.Request.UserLanguages[0];
    Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureName);
}

Is this the best place to set CurrentUICulture and is Request.UserLanguages[0] the best place to get that info?


Update:

Ariel's post shows this can be defined without code, using web.config

<system.web>
  <!--If enableClientBasedCulture is true, ASP.NET can set the UI culture and culture for a Web page automatically, based on the values that are sent by a browser.-->
  <globalization enableClientBasedCulture="true" culture="auto:en-US" uiCulture="auto:en"/>
like image 616
Robert Claypool Avatar asked Oct 27 '09 22:10

Robert Claypool


2 Answers

Here is a sample using an HttpModule:

http://weblogs.manas.com.ar/smedina/2008/12/17/internationalization-in-aspnet-mvc/

Other options, create a base Controller class and implement the localization logic there. Or use an action filter attribute, but you'll have to remember to add it on every controller or combine this approach with the base Controller class.

like image 184
Ariel Popovsky Avatar answered Nov 20 '22 05:11

Ariel Popovsky


Request.UserLanguages[0] can only be a hint what language the users wishes to see. Most users dont know where to change the browser language.

Another point: Dont be sure that Request.UserLanguages[0] is a valid language. It can even be null. (Not sure what bots have there)

You usually have a Language chooser on the page. Once a user has selected a language there, it is stored in a cookie, session or url. I like to use url because I think it looks pretty.

If a user sees your page without having set a language on your page, you should check if Request.UserLanguages[0] is a language you support and set Thread.CurrentThread.CurrentUICulture.

I use a filter to set Thread.CurrentThread.CurrentUICulture. Thats ok as long as no other filter is using Thread.CurrentThread.CurrentUICulture. Otherwise you would need to set the right execution order for filters.

I also use Matts helper and it worked very well so far.

like image 6
Mathias F Avatar answered Nov 20 '22 04:11

Mathias F