【问题标题】:Match route with optional action将路由与可选操作匹配
【发布时间】:2015-09-15 20:31:47
【问题描述】:

我有一个页面应该接受两个 url,一个没有动作,应该有默认值“索引”,一个有一个应该链接到用户给定动作的动作。

链接:

  • 第三方/测试/3
  • 第三方/测试/索引/3

我想出了以下路线:

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

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

  • SpamReferral/Test/Index/3

现在我已经给动作一个默认值“索引”,我认为它会匹配路由,但事实并非如此。我只是得到一个 404。

为什么它不匹配没有“索引”操作的路由? 我正在使用 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 });

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 routes url-routing asp.net-mvc-routing


    【解决方案1】:

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

    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} 后面跟着另一个占位符。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-28
      • 1970-01-01
      • 2015-08-25
      相关资源
      最近更新 更多