动态设置区域性信息



我正在asp.net/c#中构建一个应用程序。对于应用程序中的日期,我使用全局变量,这些变量提供给定数据库中的日期格式。

因此,如果我的DateFormat是英国的,我会使用:

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

如果是美国,我使用:

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

因此,使用这种方法对我的日期进行了验证和比较。我的问题是;我应该只为整个应用程序检查一次格式吗?还是必须检查每个页面的格式,因为我知道每个新线程的CultureInfo都会重置?

你能建议一下做这件事的正确方法吗。

这需要为每个请求完成。您可以编写一个HttpModule,为每个请求设置当前线程区域性。

**每个请求都是一个新的线程

EDIT:添加了示例。

让我们按照如下方式创建一个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>

现在,如果我们像这样浏览url(假设MVC中的默认路由指向Home/index和端口78922)

  1. http://localhost:78922/Home/Index-文化将"在美国"

  2. http://localhost:78922/Home/Index/cs-文化将是"cs CZ"

  3. http://localhost:78922/Home/Index/fr-文化将是"fr-fr"

***只是一个例子,使用您的逻辑设置文化。。。

您只需要为会话设置一次

http://support.microsoft.com/kb/306162

最新更新