How to route a multiple language URL with a MVC

后端 未结 4 1366
执念已碎
执念已碎 2020-12-08 15:53

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

4条回答
  •  一向
    一向 (楼主)
    2020-12-08 16:20

    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)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            //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 rt = db.RoutingTranslations.ToList();
                foreach (var r in rt)
                {
                    routes.MapRoute(
                        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
            routes.MapRoute(
                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)

提交回复
热议问题