I got this code to retrieve the browser language that was set by the user:
string cultureName = string.Empty;
try
{
string[] languages = HttpContext.Current.Request.UserLanguages;
cultureName = languages[0].ToLowerInvariant().Trim();
}
catch
{
cultureName = "en-US";
}
System.Globalization.CultureInfo browserCulture = CultureInfo.CreateSpecificCulture(cultureName);
System.Threading.Thread.CurrentThread.CurrentCulture = browserCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = browserCulture;
I got these errors:
-
Culture name 'name' is not supported: From our error logs, found out that name isx-ns1xs4m8wixnxg,x-ns1dfk__jmpnx0etc.. I do not know where this languages come from, or what are they, but I think these languages are retrieved when browsing from mobile. -
The name 'name' contains characters that are not valid for a Culture or Region: Also found out that name isfr; q=1.0,en;q=1.0,en_us,en;q=0.9, etc… I’m thinking that I should parse it per character to see if it is a valid
I have already modified my code to handle these errors:
CultureInfo cultureInfo;
try
{
string[] languages = HttpContext.Current.Request.UserLanguages;
string cultureName = languages[0].ToLowerInvariant().Trim();
cultureInfo = CultureInfo.CreateSpecificCulture(cultureName);
}
catch
{
cultureInfo = CultureInfo.CreateSpecificCulture("en-US");
}
System.Globalization.CultureInfo browserCulture = cultureInfo;
System.Threading.Thread.CurrentThread.CurrentCulture = browserCulture;
System.Threading.Thread.CurrentThread.CurrentUICulture = browserCulture;
but I would like to know where these languages came from, or how to replicate them? This is to verify if my code is working properly. Thanks.
The only thing you should be aware of that
UserLanguageswill simply return corresponding HTTP header. Header values may have additional attributes separated by;. So you should split that value on;and get the first bit.As for
x-ns1dfk__jmpnx0I would say ignore it. Falling back to your default language in this case is totally valid.edit: I take the first part back. According to this the q parameter is the value of the language preference. So what you really should do is split on semicolon, then parse value of q attribute (assume 1 if not present), then sort on it and take the first one.