CultureInfo.CurrentCulture给了我错误的文化

thc*_*ver 8 c# cultureinfo currentculture

我正在尝试获取客户的国家/地区,因此我使用CultureInfo.CurrentCulture.问题是,当我的加拿大客户使用我的网站时,他们会显示为美国人.

看起来CultureInfo.CurrentCulture正在返回我服务器的国家而不是他们的国家.那么我如何获得客户的国家?

Tho*_*que 18

您只需要在web.config文件中设置culture属性auto:

<system.web>
    <globalization culture="auto" />
<system.web>
Run Code Online (Sandbox Code Playgroud)

这将自动设置CurrentCulture为客户的文化.

如果您使用的是本地化资源,也可以设置uiCultureauto.


DOK*_*DOK 2

我相信您需要编写代码来从传入的浏览器请求中读取用户的文化,并从中设置您的 CultureInfo 。

这个家伙描述了他们是如何做到这一点的:将当前线程的显示区域性设置为来自用户传入的 Http“请求”对象的最合适的区域性。

他在那里进行了精彩的讨论,但他基本上是这样做的:

在 中Page_Load,他们进行了这样的调用:UIUtilities.setCulture(Request);

这就是所谓的:

/// 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);
}
Run Code Online (Sandbox Code Playgroud)