简体   繁体   中英

CultureInfo.CurrentCulture is giving me the wrong culture

I'm trying to get my clients' country, so I use CultureInfo.CurrentCulture. Problem is that when my Canadian customers use my website, they're showing up as American.

It looks like CultureInfo.CurrentCulture is returning my server's country instead of their country. So how do I get my clients' country?

You just need to set the culture attribute to auto in your web.config file:

<system.web>
    <globalization culture="auto" />
<system.web>

This will automatically set the CurrentCulture to the client's culture.

You can also set uiCulture to auto if you're using localized resources.

I believe you need to write code to read the user's culture from the incoming browser request , and set your CultureInfo from that.

This fellow describes how they do it : Set the display culture for the current thread to the most appropriate culture from the user's incoming Http "request" object.

He has an excellent discussion there, but this is basically how he does it:

In Page_Load , they make this call: UIUtilities.setCulture(Request);

Where this is what gets called:

/// Set the display culture for the current thread to the most
/// appropriate culture from the user's incoming Http "request" object.
internal static void setCulture(HttpRequest request)
{
    if (request != null)
    {
      if (request.UserLanguages != null)
      {
        if (request.UserLanguages.Length > -1)
        {
          string cultureName = request.UserLanguages[0];
          UIUtilities.setCulture(cultureName);
        }
      }
        // TODO: Set to a (system-wide, or possibly user-specified) default
        // culture if the browser didn't give us any clues.
    }
}

/// Set the display culture for the current thread to a particular named culture.
/// <param name="cultureName">The name of the culture to be set 
/// for the thread</param>
private static void setCulture(string cultureName)
{
    Thread.CurrentThread.CurrentCulture = 
        CultureInfo.CreateSpecificCulture(cultureName);
    Thread.CurrentThread.CurrentUICulture = new
        CultureInfo(cultureName);
}

In my case my machine originally had English - UK installed. I added the English - US language and set it as default. I also verified that US was set correctly in the registry. Sadly, System.Threading.Thread.CurrentThread.CurrentCulture still displayed the wrong culture, UK. I discovered you need to set the language options. Download the language pack, handwriting and speech.

Even then the culture was incorrect. The UK would show up all over the machine and after I installed the US language pack the start menu went completely nuts. I gave up and reinstalled the OS using an english-US version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM