Translation of MVC routes

With ASP.Net MVC 4 I am wanting to translate all my routes, currently some are like this:

http://localhost/pt-br
http://localhost/pt-br/sobre
http://localhost/pt-br/usuario/cadastro

I am adding the English language and would like to use the same Controller / Action and only change the route to:

http://localhost/en-us
http://localhost/en-us/about
http://localhost/en-us/user/create

I did some Google searches, but found nothing like this case. Not least because my second route is custom and almost all my routes are. I would just like to know which is better way to develop it.

Author: gmsantos, 2015-01-11

1 answers

1. Make a resource file for routes only

In this case, standardize your system so that each Resource String is the name of a Controller or the name of a action. It's okay if you repeat it.

2. Make a route file for each culture

This step is optional, but it helps you get organized. Make a class for each route involving culture that you would like your system to have:

namespace SeuProjeto
{
    public class PtBrRouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "SobrePtBr",
                url: "pt-br/Sobre/{action}/{id}",
                defaults: new { controller = "About", action = "Index", id = UrlParameter.Optional }
            );

            ...

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

3. Try mapping dynamic

Once the separation is done, you can be the resources file using something like this to assemble your routes:

var resourceSet = MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
    routes.MapRoute(
                name: entry.Value,
                url: "pt-br/" + entry.Value + "/{action}/{id}",
                defaults: new { controller = entry.Key, action = "Index", id = UrlParameter.Optional }
            );
}
 1
Author: Leonel Sanches da Silva, 2015-01-11 21:12:54