4

Each user of my application will choose their country, after which it will be stored in a cookie and stored for later requests. Everything is working OK, but I need to set the culture at the start of a session. I'm currently experimenting by setting the culture in the web.config to be en-GB and then using the Global.asax to override the culture for the session to en-US. Code below

protected void Session_Start(object sender, EventArgs e)
    {
        if (Globals.CountryID == 8)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
            Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
        }
    }

The countryID is 8, and the culture is set to en-US in the following code. However, when I navigate to a page that has ToString("C") set, it still displays in GBP and the culture is still en-GB.

Any suggestions?

Niklas
  • 13,005
  • 23
  • 79
  • 119
Paul
  • 3,072
  • 6
  • 37
  • 58

2 Answers2

8

You are assuming that the thread that will service the page request is the same thread that has started the session as in your code - this is not guaranteed.

You may want to save the culture in a Session variable and use an override InitializeCulture in your pages, as described in: How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • So I need to do this on every page, or create a base page for every other page to inherit from? Damn, I have over 700 pages in my application. – Paul Dec 13 '11 at 10:54
  • @Paul - Yes, those are your options. A base page is probably the best option. – Oded Dec 13 '11 at 10:55
  • 1
    unfortunately you still need to do something for WebMethods. Ajax calls don't go through the Page initialization. – Garr Godfrey Sep 24 '15 at 23:50
1

You must set the culture on each call, Session_Start is only fired when a session is created. So your culture is correct only on first call or when the session is recreated.

lnu
  • 1,404
  • 1
  • 9
  • 25