如何使用不同路径名开始的两个MVC路由在MVC4中使用相同的控制器

时间:2020-12-12 20:55:20

I have the following routes:

我有以下路线:

   routes.MapRoute(
      name: "One",
      url: "admin/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   );
   routes.MapRoute(
      name: "Two",
      url: "home/{id}",
      defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
   );

Is there a way that I can combine these routes into just one route where the they both direct to the "Home" controller?

有没有办法可以将这些路线合并到一条路线中,它们都指向“Home”控制器?

1 个解决方案

#1


1  

Try

尝试

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

works for me

适合我

answer on comment. what a problem add the constraint?

回答评论。什么问题添加约束?

 routes.MapRoute(
           name: "Default2",
           url: "{section}/{id}",
           defaults: new { section = "home", controller = "Home", action = "Index", id = UrlParameter.Optional },
           constraints: new { section = "admin|home" }
       );

#1


1  

Try

尝试

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

works for me

适合我

answer on comment. what a problem add the constraint?

回答评论。什么问题添加约束?

 routes.MapRoute(
           name: "Default2",
           url: "{section}/{id}",
           defaults: new { section = "home", controller = "Home", action = "Index", id = UrlParameter.Optional },
           constraints: new { section = "admin|home" }
       );