Search code examples
asp.netasp.net-mvcglobalization

Thread.CurrentThread.CurrentUICulture Vs Accept-Language in ViewModels


Globalization: The reason for asking this question is to have a better understanding of how Thread.CurrentThread.CurrentUICulture works in relation to properties and error messages in ViewModels and Controllers

I have setup my project and overrides OnActionExecuting method of my controllers I have set the language based on user selection stored in cookie.

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    base.OnActionExecuting(filterContext);

    HttpCookie cookie = Request.Cookies["lang"];

    string lang = cookie != null ? cookie.Value : "en-US";
    System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(lang);
}

Now, after this, checking the Accept-Language header in http request being sent by the browser, the user changes was not reflected - value is still "en-US". It makes me feel that these two are not dependent.

I have also moved the code to Global.asax but it's the same effect. Been on since yesterday.

The Thread.CurrentThread.CurrentUICulture setting affects texts on page but not error messages or properties from ViewModel annotations. But when the Accept-Language is changed from the browser, then the error messages are picked from the right resourse files.

  • Is it possible to manipulate the Accept-Language header? - this seems to be read-only
  • Main Question: how does the Thread.CurrentThread.CurrentUICulture works? It seems to be what most examples/articles/blogs etc. on the internet use.

Solution

  • In order to get globalization right on a public site with ASP.NET MVC, I recommend the following:

    • Use (a fragment of) the URL to determine the culture, not a cookie. Otherwise it will not be possible to link to a page in a pre-defined language, and search engines will have trouble indexing your content.
    • Browser preferences can be used to redirect to the appropriate language on first visit (for example, when calling the homepage without any URL fragment: www.mysite.com redirects to www.mysite.com/en-US/ for users with en-US preferences in the browser)
    • OnActionExecuting is too late for culture initialization. I recommend reading Alex Adamyan's article about localization in ASP.NET MVC, and implement a custom route handler to initialize the UiCulture/Culture. This will also work correctly with Modelbinding (for example, when using resources and attributes on view model classes).

    As to your other questions: It doesn't really make sense to modify the Accept-Language headers since the client sends them to the server. Even if you could modify them, the client would never know about it.