asp.net-mvc – MVC route translation

Question:

With ASP.Net MVC 4 I want 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'm adding the English language and I would like to use the same Controller/Action and just 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 I didn't find anything like this case. Also because my second route is customized and almost all of my routes are. I would just like to know what is the best way to develop this.

Answer:

1. Make a Resource file for routes only

In this case, standardize your system so that each Resource String is either the name of a Controller or the name of an Action . It's okay to repeat yourself.

2. Make a route file for each culture

This step is optional, but it helps you get organized. Take a class for each route involving culture 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 to do dynamic mapping

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 }
            );
}
Scroll to Top