Translation of MVC routes

Asked

Viewed 375 times

3

With the 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 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 couldn’t find anything like this case. Because my second route is personalized and almost all my routes are. I would just like to know what is the best way to develop this.

1 answer

1

1. Make a Resource file for routes only

In this case, program your system so that each Resource String is the name of a Controller or the name of a Action. It’s okay to repeat.

2. Make a route file for each culture

This step is optional, but it helps you get organized. Make a class for each culture-based route you’d 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. Seek dynamic mapping

Made the separation, 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 }
            );
}
  • Thank you @Gypsy for your reply, I will develop here then share the result.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.