我正在asp.net/c#中构建一个应用程序。对于我的应用程序中的日期,我使用全局变量,它给出了给定数据库中的日期格式。
所以如果我的DateFormat
是英国人,我会使用:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-GB");
如果是美国我使用:
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
所以我的日期经过验证并使用这种方法进行比较。我的问题是;我应该只为整个应用程序检查一次格式,还是必须检查每个页面的格式,因为我知道每个新线程CultureInfo
都会被重置?
请您建议正确的方法。
答案 0 :(得分:0)
您只需为会话设置一次
答案 1 :(得分: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>
现在,如果我们浏览网址,(假设MVC中的默认路由指向Home / index和端口78922)
http://localhost:78922/Home/Index - 文化将是“en-US”
http://localhost:78922/Home/Index/cs - 文化将是“cs-CZ”
http://localhost:78922/Home/Index/fr - 文化将是“fr-FR”
* **只是一个例子,使用你的逻辑设置文化 ......