I need to add the culture to the url to support localization in my asp.net mvc application with url's like: sample.com/en/about
sample.com/en/product/2342
I recently upgraded my app from MVC 5.0 to 5.1 but the routing did not work as expected so I created a fresh asp.net mvc 5.0 test application and got the culture to show up in the url in a matter of minutes. However as soon as I upgrade this test application to MVC 5.1 the culture is no longer generated in links and if you manually type it into the url you get a 404 error.
I zipped up my 5.0 and 5.1 test applications here. I need help understanding why this doesn't work in MVC 5.1 and how to correct it. Perhaps my understanding of routing is flawed or this is a legitimate bug with 5.1?
In this test application the Home/About action has a routing attribute applied to it [Route("about")] and it's expected that when the link for that route is generated it should be localhost/en/about but instead it's just localhost/about. If you type localhost/en/about into the address bar you'll get a 404 error in the Mvc 5.1 test application.
Here is the relevant code that does work in MVC 5.0:
public class RouteConfig
{
private const string STR_Culture = "culture";
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.LowercaseUrls = true;
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{culture}/{controller}/{action}/{id}",
defaults: new { culture = "en", controller = "Home", action = "Index", id = UrlParameter.Optional }
);
foreach (var item in routes)
{
// this works in MVC 5.0
if (item is Route)
{
var route = item as Route;
if (route.Url.IndexOf("{" + STR_Culture + "}") == -1)
route.Url = String.Format("{{{0}}}/{1}", STR_Culture, route.Url);
//AddCulture(route.Defaults);
}
}
}
private static void AddCulture(RouteValueDictionary dictionary)
{
if (dictionary == null)
dictionary = new RouteValueDictionary();
if (dictionary.ContainsKey(STR_Culture) == false)
dictionary.Add(STR_Culture, "en");
}
}
for-loopand the call to the method, are you simply defaulting the culture to "en"? Can't tell what that's doing.