Search code examples
asp.net-mvc-3localizationglobalization

Change route segment dynamically in mvc3


I created 2 routes like this to perform the localize:

routes.MapRoute(
                "Default", // Route name
                "{language}/{controller}/{action}/{id}", // URL with parameters
                new { language = "en", controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
               );

routes.MapRoute(
                "Default2", 
                "{language}/{controller}/{action}/{id}/{slug}",
                new { language = "en", controller = "Home", action = "Index", id = UrlParameter.Optional, slug = UrlParameter.Optional }
               );

Now I got 2 problems:

  1. The default www.mydomainname.com doesn't automatically add en to URL. Desire result: when I enter www.mydomainame.com it should automatically change to www.mydomainname.com/en.

  2. When I change the culture. How can I replace the default language segment's value on the route by TwoLetterISOLanguageName of that culture?

Please advice


Solution

  • This is an approximate annswer so I hope it gets you on the right track.

    CultureInfo.TwoLetterISOLanguageName is a non static field and will depend on the user, so you're going to have to use a redirect to achive this (it cant be set in the global.asax file).

    One way to to this is when the user requests the domain name, use the normal default route to route them to the home controller

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

    Within the home controller, redirect them to the proper route

     public ActionReult Index(){
        var routeDataDict = HttpContext.Request.RequestContext.RouteData.Values;
        routeDataDict.Add("language", CultureInfo.TwoLetterISOLanguageName);
        Response.RedirectToRoute(routeDataDict);
     }