2010-06-28 49 views
8

我試圖讓我的客戶的國家,所以我使用CultureInfo.CurrentCulture。問題是,當我的加拿大客戶使用我的網站時,他們顯示爲美國人。CultureInfo.CurrentCulture給了我錯誤的文化

它看起來像CultureInfo.CurrentCulture返回我的服務器的國家,而不是他們的國家。那麼,我如何獲得我的客戶的國家?

回答

2

我相信你需要編寫代碼到從傳入的瀏覽器請求中讀取用戶的文化,並從中設置你的CultureInfo。

This fellow describes how they do it:將當前線程的顯示區域設置爲來自用戶的傳入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); 
} 
+0

在正確的行上,但請注意,瀏覽器發送的Accept-Language頭不一定是用戶的首選語言。我在歐洲,碰巧有美國版的Windows,所以我的IE8發送en-US。另請注意,accept-language頭文件中的名稱可能不是有效的.NET文化名稱,因此對CreateSpecificCulture的調用應放在try/catch中。 – Joe 2010-06-28 17:34:57

+0

沒有運氣。我仍然在測試中使用en- – thchaver 2010-06-28 20:57:06

+0

你從Request.UserLanguages得到什麼?也就是說,你確定你的瀏覽器正在請求什麼語言? – DOK 2010-06-28 23:03:42

18

您只需在您的web.config文件中將culture屬性設置爲auto

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

這會自動將CurrentCulture設置爲客戶的文化。

如果您使用的是本地化資源,也可以將uiCulture設置爲auto

+1

我希望我能多勞多得,多謝,謝謝。花了3小時讓我工作:) – Thousand 2013-02-15 22:31:58

1

在我的情況下,我的機器最初安裝了英國 - 英國。我添加了英語 - 美國語言並將其設置爲默認語言。我還證實美國在註冊表中正確設置。可悲的是,System.Threading.Thread.CurrentThread.CurrentCulture仍然顯示了錯誤的文化,英國。我發現你需要設置語言選項。下載語言包,手寫和語音。

即使那時文化是不正確的。英國將在整個機器上出現,並且在我安裝了美國語言包之後,開始菜單完全變得瘋狂。我放棄並重新安裝了使用英美版本的操作系統。