2012-03-06 27 views
0

我在asp.net/c#中構建了一個應用程序。對於我的應用程序中的日期,我使用了給定數據庫的日期格式的全局變量。動態設置文化信息

所以,如果我的DateFormat是英國我使用:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB"); 

如果是美國,我用:

Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); 

所以我的日期驗證,並使用這種方法進行比較。我的問題是;我應該只檢查一次整個應用程序的格式,還是必須檢查每個頁面的格式,因爲我知道每個新線程CultureInfo都會被重置?

您能否建議您這樣做的正確方法。

回答

0

這就需要爲每個請求進行設置它只是一次。您可以編寫一個HttpModule來爲每個請求設置當前線程文化。

**每個請求是一個新的線程

編輯:添加示例。

讓我們創建一個HttpModule,並設置文化。

public class CultureModule:IHttpModule 
{ 
    public void Dispose() 
    {   
    } 
    public void Init(HttpApplication context) 
    { 
     context.PostAuthenticateRequest += new EventHandler(context_PostAuthenticateRequest);   
    } 
    void context_PostAuthenticateRequest(object sender, EventArgs e) 
    { 
     var requestUri = HttpContext.Current.Request.Url.AbsoluteUri; 
     /// Your logic to get the culture. 
     /// I am reading from uri for a region 
     CultureInfo currentCulture; 
     if (requestUri.Contains("cs")) 
      currentCulture = new System.Globalization.CultureInfo("cs-CZ"); 
     else if (requestUri.Contains("fr")) 
      currentCulture = new System.Globalization.CultureInfo("fr-FR"); 
     else 
      currentCulture = new System.Globalization.CultureInfo("en-US"); 

     System.Threading.Thread.CurrentThread.CurrentCulture = currentCulture; 
    } 

} 

註冊web.config中的模塊,(在的System.Web經典模式下system.webserver集成模式。

<system.web> 
...... 
<httpModules> 
    <add name="CultureModule" type="MvcApplication2.HttpModules.CultureModule,MvcApplication2"/> 
</httpModules> 
</system.web> 
<system.webServer> 
..... 
<modules runAllManagedModulesForAllRequests="true"> 
    <add name="CultureModule" type="MvcApplication2.HttpModules.CultureModule,MvcApplication2"/> 
</modules> 

現在,如果我們瀏覽器的網址一樣,

  1. (在MVC指向主頁/索引和端口78922假定默認路由)- 文化將是 「EN-US」

  2. http://localhost:78922/Home/Index/cs - 文化將是 「CS-CZ」

  3. http://localhost:78922/Home/Index/fr - 文化將是 「FR-FR」

* * *只是一個例子,使用你的邏輯來設置文化 ...

+0

謝謝,,,請你幫我一個例子,如果可能..... .....通過你所說的做,我不需要寫它再次正確??謝謝 – freebird 2012-03-06 12:41:42

+0

當然,我會編輯帖子,包括一個例子 – Manas 2012-03-06 13:28:15

+0

,,,,非常感謝,,,它幫助了,,,,另一個疑問是我是否應該包括在一個單獨的.cs文件,是嗎? ??謝謝 – freebird 2012-03-07 05:34:47