Auto Detecting and Setting ASP.NET Locale based on Browser Locale - RickStrahl/Westwind.Globalization GitHub Wiki
In order to do automatic localization based on a browser's language used, you can sniff the browser's default language and set the UiCulture.
You can use ASP.NET to detect browser locale and set the Culture and UI culture by using the
<configuration>
<system.web>
<globalization culture="auto:en-US" uiCulture="auto:en-US" />
</system.web>
</configuration>
This will automatically switch the browser into the clients locale if possible. Otherwise, the browser locale is missing, or can't be matched to server locales it will fall back to en-US.
You can also pro grammatically set the Culture/UiCulture by explicitly setting the locale on the active thread's current CultureInfo object. You'll want to do this in the Application_BeginRequest
method of global.asax which changes the Culture/UiCulture as early as possible during page processing.
The easiest way to do this is using the WebUtils.SetCulture()
from the Westwind.Utilities library. In addition to switching the culture it also gives a few options to manage which locales are actually switched, and what currency symbol to use after the switch.
protected void Application_BeginRequest()
{
// Automatically set the user's locale to what the browser returns
// and optionally only allow certain locales/locale-prefixes
WebUtils.SetUserLocale(allowLocales: "en,de,fr", currencySymbol: "$");
}
This forces the user's Culture and UI Culture to whatever the browser is using, and explicitly. Now when a page is rendered it will use the UiCulture of the browser. The optional allowLocales enforces that only certain locales can be set - anything not matched doesn't switch the browser. This avoids unnecessary culture switching and formatting for locales that your application doesn't actually have support for. It also avoids issues with some problem locales like Turkish that can affect upper/lower case string comparison issues.
If you leave out the parameters, the behavior of SetUserLocale() is identical to the web.config settings meaning locale is always switched.
The way .NET resource managers work, if there's no match for the locale the user provides, resources fall back to the closest matching locale or the invariant locale.
For example:
If a request comes in for Italian (it-IT) but we have no Italian resources:
it-IT - no resources present
it - fallback - no resources present
invariant - resources found value served
If a request comes in for Swiss German (de-CH) when we have generic German resources:
de-CH - no resources present
de - resource found, value returned
Note that Invariant is the 'empty' locale - the one that has an empty LocaleId in the localization table (or no-locale extension on a Resx file). Typically this is what you use for your 'default' language like English that everything that doesn't match falls back to.
Resource Fallback tries to ensure that always something is returned.