While processing http request in a ASP.NET application, the current culture of the thread on which the request is processing, depends on the language settings of the browser.
For example, if the user has set languages [de-de], [en-us] and [bs-Latn-ba] in his browser, then property
Request.UserLanguages will contain the list of same languages.
You can use these values to process the request in the culture, which depends on user browser settings and application logic.
However, by default the first language in the list will define the culture of the thread, which is processing the request.
This is all fine, but there is a case, which could cause some formatting errors. That happens when the user has set a neutral culture like [de] or [bs]. In that case the thread culture will be set on the neutral culture. Unfortunately there are many formatting functions in .NET (e.g. DateTime.Parse) which do not understand neutral cultures.
This example shows hot to check whether the current culture is neutral one:
Thread.CurrentThread.CurrentUICulture.IsNeutralCulture
In other words, when the user has chosen the neutral culture, it is likely possible that your ASP.NET application will file while doing some formatting.
To work around this you can set specific culture from neutral one, before request gets processed:
protected void Application_BeginRequest(Object sender, EventArgs e) { Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(Thread.CurrentThread.CurrentUICulture.Name); } |
This is very simple solution, which unfortunately has one hidden issue. ASP.NET framework under the hub will in some cases (for example dynamic loading of controls) rewrite the thread’s culture again (over and over again).
To work around this do following:
protected void Application_BeginRequest(Object sender, EventArgs e) { Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(Thread.CurrentThread.CurrentUICulture.Name); Request.UserLanguages[0] = Thread.CurrentThread.CurrentUICulture.Name; } |
Note: If other browser supported languages also have to be processed somewhere in the application logic, the last line should overwrite all of languages and not the first one only!
Posted
Feb 18 2009, 12:59 AM
by
Damir Dobric