使用 HttpModule 进行本地化安全吗?
我正在考虑使用 HttpModule 进行本地化(基于 这篇文章) - 但我很好奇,这安全吗?
以下是代码,供参考:
public class CookieLocalizationModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
// eat the cookie (if any) and set the culture
if (HttpContext.Current.Request.Cookies["lang"] != null)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["lang"];
string lang = cookie.Value;
var culture = new System.Globalization.CultureInfo(lang);
// is it safe to do this in all situations?
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}
}
我的印象是多个线程可能会为 Web 请求提供服务。像这样在 HttpModule 中设置当前/当前 UI 文化是否安全,并在 Web 请求的生命周期内尊重它,无论有多少线程参与服务它?
更新:
我已经在生产中使用这种方法近一年了,所以我当然可以验证使用 HttpModule 进行本地化是完全安全的。
I'm considering making use of an HttpModule for localization purposes (based on the example in this article) - but I'm curious, is this safe?
Here's the code, for reference:
public class CookieLocalizationModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
// eat the cookie (if any) and set the culture
if (HttpContext.Current.Request.Cookies["lang"] != null)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["lang"];
string lang = cookie.Value;
var culture = new System.Globalization.CultureInfo(lang);
// is it safe to do this in all situations?
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
}
}
}
I was under the impression that multiple threads could potentially service a web request. Is it safe to set the Current/Current UI Cultures in an HttpModule like this and have it respected for the life of the web request regardless of how many threads are involved in servicing it?
Update:
I have been using this method in production for nearly a year now, so I can certainly verify that it is perfectly safe to use an HttpModule for localization.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,这应该没问题。
我非常确定只有一个线程将为请求提供服务,除非您显式启动另一个线程,在这种情况下,区域性(和其他内容)将被复制到另一个线程。
Yes, this should be fine.
Im pretty sure that only one thread will service a request, unless you explicitly start another, and in that case, the culture (and other things) are copied to the other thread.