繁体   English   中英

动态设置文化信息

[英]Setting culture info dynamically

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

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

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

如果是美国,我使用:

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

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

您能否建议正确的做法。

您只需为会话设置一次

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

这需要针对每个请求完成。 您可以编写一个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>

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

  1. http:// localhost:78922 / Home / Index-文化将成为“ zh-CN”

  2. http:// localhost:78922 / Home / Index / cs-文化将为“ cs-CZ”

  3. http:// localhost:78922 / Home / Index / fr-文化将为“ fr-FR”

* **仅是示例,使用您的逻辑来设置文化 ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM