I am working on localizing my static website in multiple languages. I've already added two resource (.resx) files, Strings.resx
and Strings.es.resx
.
I have a RouteConfig, like this:
var language = System.Threading.Thread.CurrentThread.CurrentUICulture.Name;
routes.MapRoute(
name: "Default",
url: "{lang}/{controller}/{action}/{id}",
constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" },
defaults: new { lang = language, controller = "app", action = "index", id = UrlParameter.Optional }
);
I also have the following Filter setup:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new LocalizationAttribute("en"), 0);
}
}
Which uses this attribute:
public class LocalizationAttribute : ActionFilterAttribute
{
private string mDefaultLanguage = "en";
public LocalizationAttribute(string defaultLanguage)
{
mDefaultLanguage = defaultLanguage;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string lang = (string)filterContext.RouteData.Values["lang"] ?? mDefaultLanguage;
if (lang != mDefaultLanguage)
{
try
{
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture = new CultureInfo(lang);
}
catch (Exception)
{
throw new NotSupportedException(string.Format("ERROR: Invalid language code '{0}'.", lang));
}
}
}
}
When I navigate to my home page with this, it defaults to the English language, and the URL looks like http://example.com/
.
When I navigate to any other action, it changes the URL to: http://example.com/en-us/register
, for example. If I remove the en-us
from the URL, and just make it http://example.com/register
, I get a 404
.
Note, if I change the URL to http://example.com/es/
and http://example.com/es/register
, it works as expected. I'd just like the default to be English, even when en
or en-us
isn't supplied.