将路由与可选操作匹配

Match route with optional action

我有一个页面应该接受两个 url,一个没有动作,应该有默认值 "Index",另一个有动作,应该 link 给用户给定的动作。

link组:

我想到了以下路线:

 RouteTable.MapRoute("ThirdParty", "{thirdParty}/{controller}/{action}/{type}",
           new { action = "Index" },
           new { thirdParty = "^[a-zA-Z0-9]*$", type = @"\d+" },
           new[] { @namespace });

不幸的是,这只匹配以下路线:

现在我已经为操作指定了默认值 "Index",我认为它会匹配路线,但事实并非如此。我刚收到 404。

为什么不匹配没有"Index"动作的路由? 我正在使用 ASP.NET MVC 4.


创建 2 条路线工作正常,但我很确定它应该在一条路线上工作。

    RouteTable.MapRoute(name, "{thirdParty}/{controller}/{type}",
         new { action = "Index"},
          new { thirdParty = "^[a-zA-Z0-9]*$", type = @"\d+" },
         new[] { @namespace });

        RouteTable.MapRoute(name + "(2)", "{thirdParty}/{controller}/{action}/{type}",
            new { action = "Index" },
            new { thirdParty = "^[a-zA-Z0-9]*$", type = @"\d+"},
            new[] { @namespace });

制作一条可以做所有事情的路线绝不是最佳做法。如果创建两条路线可以满足您的需要,那么这是最好的解决方案。

RouteTable.MapRoute(name, "{thirdParty}/{controller}/{type}",
     new { action = "Index"},
      new { thirdParty = "^[a-zA-Z0-9]*$", type = @"\d+" },
     new[] { @namespace });

RouteTable.MapRoute(name + "(2)", "{thirdParty}/{controller}/{action}/{type}",
    new { action = "Index" },
    new { thirdParty = "^[a-zA-Z0-9]*$", type = @"\d+"},
    new[] { @namespace });

此外,不可能将可选的占位符放在路由模式的中间 - 它只能作为最右边的位置。因此,使用 MapRoute 的单个路由不可能实现您的要求,因为 {action} 后跟另一个占位符。