
Brandon K. answered 12/27/19
Senior Software Engineer with 15 years experience in ASP.NET
There are a couple of different options, but the most common practice is to create a folder in your ASP.NET project called Resources and add .resx files to it containing all of the text in your web site / app. Organisation can vary, but you would generally have a particular .resx correspond to a single view and maybe have a shared Global.resx. Then, for an alternative locale / language, you create a copy of the original and put the locale in the filename before the final file extension. For example:
Index.resx
Index.es-mx.resx
Make sure to set the Access Modifier for the files to Public and the Custom Tool Namespace to "Resources"
In the markup, you would access the string resources such as:
@Resources.Index.Title
where Title is the name of a string resource in the resx file.
You then have to add an override to the Global.asax.cs file along these lines:
protected void Application_AcquireRequestState(object sender, EventArgs e)
{
string culture = "en-US";
if (Request.UserLanguages != null)
{
culture = Request.UserLanguages[0];
}
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(culture);
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture);
}
Notice - this works OK if the user only has the other language in their settings, but if en-us is in your browser's list of languages (and especially if it is near the top of the list), MVC may tend to deliver the default resources. Another approach would be to give each supported locale / language a different area, and in the area you set the CurrentCulture. This would allow users to explicitly go to a particular language even if their browser does not have it in its list. It also allows more flexibility in the views that are delivered. You would not have to repeat all of the View and Controller code from the root as it will fallback to the root views and the controllers can inherit directly from their root equivalents. But if you wanted to override a View so that the layout is cleaner for a particular language, you could easily do that by only overriding that one view.