Search code examples
routesasp.net-mvc-5globalization

ASP.NET MVC 5 Internationalization - culture allways default


I followed this great article about ASP.NET MVC 5 Internationalization (refered by asp.net site): http://afana.me/post/aspnet-mvc-internationalization.aspx

After implementing, I have just one problem that I can't solve. In MVC5, using the culture in urls (NOT using cookies), the culture is allways the default, never getting the users prefered languages sent by browser.

In more detail: The problem is the defauls for culture in MapRoute, that start with the default hardcoded culture for site. Then in the BeginExecuteCore the RouteData.Values["culture"] is allways filled with the default culture, never getting culture from Request.UserLanguages. The RouteData.Values["culture"] is filled even if the culture is not present in the url, at first site root access for example.

How to correctly change this behavior?

Maybe creating 2 Routes, one without culture?

Associated code:

routes.MapRoute(
        name: "Default",
        url: "{culture}/{controller}/{action}/{id}",
        defaults: new {culture = CultureHelper.GetDefaultCulture(), controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
    string cultureName = RouteData.Values["culture"] as string; 

    // Attempt to read the culture cookie from Request
    if (cultureName == null)               
        cultureName = Request.UserLanguages != null && Request.UserLanguages.Length > 0 ? Request.UserLanguages[0] : null; // obtain it from HTTP header AcceptLanguages
     //...
}

Solution

  • I discovered the solution, need to add another mapRoute (the mvc default for site root access), and coment the default value for culture route, route order is important, everything works good now:

    public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
                //Route order is important! First need to put culture route.
    
                //support for diferent languages/cultures
                routes.MapRoute(
                    name: "CultureEnabled",
                    url: "{culture}/{controller}/{action}/{id}",
                    defaults: new { /*culture = CultureHelper.GetDefaultCulture(),*/ controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
    
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
            }