Setting culture for session

2020-04-09 13:14发布

问题:

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?

回答1:

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.



回答2:

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.