CurrentCulture can not be set to Neutural Culture
var c = CultureInfo.GetCultureInfo("en"); Console.WriteLine(c.Name); //en var c2 = CultureInfo.CreateSpecificCulture("en"); Console.WriteLine(c2); //en-US Thread.CurrentThread.CurrentCulture = c2; //ok //following with throw //System.NotSupportedException: Culture 'en' is a neutral culture. Thread.CurrentThread.CurrentCulture = c;
Because of this, the following code is necessary
if (Request.UserLanguages != null && Request.UserLanguages.GetLength(0) > 0) { CultureInfo cultureInfo = new CultureInfo(Request.UserLanguages[0]); Thread.CurrentThread.CurrentUICulture = cultureInfo; Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(cultureInfo.Name); }
This code gets the user's language preference from the first element of the Request.UserLanguages array. If the user's settings are such that, Request.UserLanguages[0] will be "en-US". We create a new CultureInfo object and assign it to CurrentUICulture. The next line uses CultureInfo.CreateSpecificCulture to create a specific culture from a potentially neutral culture. In this example the culture will be no different (i.e., it will be "en-US"), but if the original language preference was "en", the specific culture would be "en-US". Recall that this step is necessary because CurrentCulture must be culture-specific. Later in this chapter, we implement a more sophisticated version of this first attempt that iterates through each of the language preferences looking for a language that matches the application's supported languages.