0

我正在研究 MVC 4 应用程序并在 route.config 中映射 URL。我想用 50 个不同的路由名称创建路由,我想在 route.config 中运行一个 for 循环,如下所示。

for (int i = 1; i <= 50; i++)
 {


string routeChildLink = "URLRoute" + i.ToString();
  string pathChildLink = menuSubChild.pageid.ToString() + "/" + menu.title.Replace(" ", "_") + "/" + menuChild.title.Replace(" ", "_") + "/" + menuSubChild.title.Replace(" ", "_") + "/" + i;
  routes.MapRoute(routeSubChildLink, pathSubChildLink, new { controller = "home", action = "index" });

 }

但是,当我运行站点时,会出现一条错误消息,指出“名为‘URLRoute1’的路由已经在路由集合中。路由名称必须是唯一的。” For 循环不起作用。

请帮忙。

谢谢

4

2 回答 2

0

The Framework always tries to match the URL of the request to a route in the order of the Routes added to the RouteCollection.

So you should put the custom routes before the default route,

public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            for (int i = 1; i <= 50; i++)
            {
                string routeChildLink = "URLRoute" + i.ToString();
                //Custom route
                routes.MapRoute(
                                   name: "Route name",
                                   url: "URL with parameters",
                                   defaults: new { controller = "Home", action = "MethodName" }
                               );
            }

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

    protected void Application_Start()
            {
                AreaRegistration.RegisterAllAreas();

                RegisterGlobalFilters(GlobalFilters.Filters);
                RegisterRoutes(RouteTable.Routes);
            }
于 2013-07-26T06:39:34.257 回答
0

利用

路由调试器查看正在创建和调用的路由

http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx

看起来该循环被第二次调用。MapRoute 表中已经有 URLRoute1。

于 2013-07-26T06:03:54.623 回答