2012-03-06 28 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