代码之家  ›  专栏  ›  技术社区  ›  Oundless

ASP.NET MVC URL路由

  •  6
  • Oundless  · 技术社区  · 15 年前

    在ASP.NET MVC中,是否可以定义路由,以便根据URL部分的数据类型确定要使用的控制器?

    例如:

    routes.MapRoute("Integer", "{myInteger}", new { controller = "Integer", action = "ProcessInteger", myInteger = "" });
    
    routes.MapRoute("String", "{myString}", new { controller = "String", action = "ProcessString", myString = "" });
    

    本质上,我希望以下URL由不同的控制器处理,即使它们具有相同数量的部件:

    My域/ 123

    MyMeal/ABC

    另外,上面的代码不起作用,但它表明了我想要实现的目标。

    1 回复  |  直到 15 年前
        1
  •  7
  •   George Stocker NotMe    15 年前

    是的,如果你用 constraints :

    像这样:

     routes.MapRoute(
                    "Integers",
                    "{myInteger}",
                        new { controller = "Integer", action = "ProcessInteger"},
                        new { myInteger = @"\d+" }
              );
    

    如果将该路由放在字符串路由之上(它不包含 @"\d+" ,然后它将筛选出包含整数的任何路由,并且任何不包含整数的路由都将通过 string 路线会接过去的。

    真正的诀窍是,路由可以根据 Regular Expressions 这就是你如何决定应该取什么。