Is it safe to use an HttpModule for localization?

2020-07-18 11:03发布

问题:

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.

回答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.