Udostępnij za pośrednictwem


Easily setting the culture on each ASP.NET request.....

Noticed something I thought was neat in the Time Tracker Starter Kit white paper - a little snippet of code that sets the culture based on the language setting of the user's browser. Here is the snippet:

// For each request initialize the culture values with
// the user language as specified by the browser.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
if (Request.UserLanguages != null)
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]);
else
// Default to English if there are no user languages
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");

   Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}

 

If  you've never checked out the code in the Starter Kits then you are missing out.

UPDATE: Check out Christian Nagel's Localization post here and here. Christian also points out that some exception handling should be added to the code above to handle the situation where someone set their locale to soemthing the Framework does not support.

This posting is provided "AS IS" with no warranties, and confers no rights.

Comments

  • Anonymous
    August 31, 2003
    You should also add an exception handling block, in case the user configured a language setting that is not supported by the Framework. e.g. et-klingon ;-)

    Also, see my localization samples:
    http://weblogs.asp.net/cnagel/posts/9753.aspx
    http://weblogs.asp.net/cnagel/posts/9751.aspx

    Christian
  • Anonymous
    February 02, 2004
    Thanks, nice snippet. What determines the Request.UserLanguages[0] that browser sends? it this the Location setting in the windows control panel Regional Settings?