I'm trying to implement localization in my ASP.NET MVC application using routing.
For example:
www.example.com/Home/Index - will show content for default culture.
www.example.com/en/Home/Index - will show english content.
www.example.com/ru/Home/Index - russian and so on...
So, I've created Localization Attribute for each action:
public class LocalizationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.RouteData.Values["lang"] != null && !String.IsNullOrWhiteSpace(filterContext.RouteData.Values["lang"].ToString()))
{
var lang = filterContext.RouteData.Values["lang"].ToString();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(lang);
}
else
{
var langHeader = String.Empty;
langHeader = filterContext.HttpContext.Request.UserLanguages[0];
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(langHeader);
Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(langHeader);
}
base.OnActionExecuting(filterContext);
}
}
I'm adding that attribute to every action in my controllers.
And registering routes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Localization",
"{lang}/{controller}/{action}/{id}",
new { lang = "en-US", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Navigation to www.example.com/About/Contacts works fine.
But when I navigate to www.example.com/en/About/Contacts or something like that, I get 404 error: resource not found.
So, what could be the problem?
Thanks in advance for your help!