Asp.net-Mvc

ASP.NET MVC:何時設置 Thread.CurrentThread.CurrentUICulture?

  • October 27, 2009

我剛剛開始本地化 ASP.NET MVC 應用程序。大多數字元串將在資源文件中定義並通過Matt 的 Localization Helpers檢索。其他字元串必須儲存在數據庫中。

我的問題: 我應該CurrentUICulture在請求管道的早期設置並在整個應用程序中使用它,還是Request.UserLanguages[0]在需要時直接使用?

現在我在想我應該CurrentUICulture在 Application_BeginRequest中設置。實現看起來像這樣:

protected void Application_BeginRequest(object sender, EventArgs e)
{
   var cultureName = HttpContext.Current.Request.UserLanguages[0];
   Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureName);
}

這是設置CurrentUICultureRequest.UserLanguages[0]最佳位置嗎?是獲取該資訊的最佳位置嗎?


更新:

Ariel 的文章顯示這可以在沒有程式碼的情況下定義,使用web.config

<system.web>
 <!--If enableClientBasedCulture is true, ASP.NET can set the UI culture and culture for a Web page automatically, based on the values that are sent by a browser.-->
 <globalization enableClientBasedCulture="true" culture="auto:en-US" uiCulture="auto:en"/>

下面是一個使用 HttpModule 的範例:

<http://weblogs.manas.com.ar/smedina/2008/12/17/internationalization-in-aspnet-mvc/>

其他選項,創建一個基本 Controller 類並在那裡實現本地化邏輯。或者使用動作過濾器屬性,但您必須記住將它添加到每個控制器上,或者將此方法與基本 Controller 類結合使用。

引用自:https://stackoverflow.com/questions/1633980