Hamid Hamid - 4 months ago 32
C# Question

How to route a multiple language URL with a MVC

I need multi-language URL route of existing controller. Let me explain more:

I have a controller with name "Product" and View with name "Software"; therefore, by default if the user enters "http://mysite.com/en/Product/Software", get right content (that really exists in http://mysite.com/Product/Software),

However, if another user -- a French user -- types "http://mysite.com/fr/Produits/logiciels", must get above controller and show with right content (same http://mysite.com/Product/Software but with French text).

Note: I set the route table with "{language}/{controller}/{action}/{id}"

Any other invalid URL must show the 404 page.

Is it possible?


Building upon Dan's post, I'm using the beneath for translating my controller and action names.

I created a table to store the values, this could and probably should be held in the resource files to keep everything together; however I used a database table as it works better with my companies processes.

CREATE TABLE [dbo].[RoutingTranslations](
[RouteId] [int] IDENTITY(1,1) NOT NULL,
[ControllerName] [nvarchar](50) NOT NULL,
[ActionName] [nvarchar](50) NOT NULL,
[ControllerDisplayName] [nvarchar](50) NOT NULL,
[ActionDisplayName] [nvarchar](50) NOT NULL,
[LanguageCode] [varchar](10) NOT NULL)

The RouteConfig.cs file was then changed to:

public class RouteConfig
    public static void RegisterRoutes(RouteCollection routes)

        //Build up routing table based from the database.  
        //This will stop us from having to create shedloads of these statements each time a new language, controller or action is added
        using (GeneralEntities db = new GeneralEntities())
            List<RoutingTranslation> rt = db.RoutingTranslations.ToList();
            foreach (var r in rt)
                    name: r.LanguageCode + r.ControllerDisplayName + r.ActionDisplayName,
                    url: r.LanguageCode + "/" + r.ControllerDisplayName + "/" + r.ActionDisplayName + "/{id}",
                    defaults: new { culture = r.LanguageCode, controller = r.ControllerName, action = r.ActionName, id = UrlParameter.Optional },
                    constraints: new { culture = r.LanguageCode }

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


By default this will always use the English controller and action names, but allows you to provide an override by entering the values into the table.

(My internationalization code is largely based from this great blog post. http://afana.me/post/aspnet-mvc-internationalization-part-2.aspx)