3

我希望能够通过一个路由约束声明访问以下内容:

/picks                        
/picks/{teamID}/{week}        
/picks/save/{teamID}/{week}   

这不适用于第二个请求:/picks/{teamID}/{week}

routes.MapRoute(
  "picks",
  "picks/{action}/{teamID}/{week}",
  new { controller = "Picks", 
        action = "Index", 
        teamID = UrlParameter.Optional, 
        week = UrlParameter.Optional });

在我看来,该操作应该默认为,Index因为我不提供一个,但我假设它实际上是在尝试找到该操作{teamID}(这是一个数字)。

如何使此约束处理所有 3 种情况?

4

2 回答 2

1

您只需要省略第一条路线的 rout 字符串中的操作:

routes.MapRoute( 
    "picks", 
    "picks/{teamID}/{week}", 
    new { controller = "Picks",  
            action = "Index",  
            teamID = UrlParameter.Optional,  
            week = UrlParameter.Optional }); 

请记住将更具体的路线放在更通用的路线之上。

例如:

"picks/{teamID}/{week}"
"picks/{action}/{teamID}/{week}"
"{controller}/{action}/{id}"

路由按照添加的顺序进行尝试。

于 2012-10-17T21:25:30.820 回答
1

查看 Phill Haack路由调试器

您还可以添加约束,以便teamId仅在它是数字时才会被拾取

routes.MapRoute(
  "picks",
  "picks/{action}/{teamID}/{week}",
  new
  {
      controller = "Picks",
      action = "Index",
      teamID = UrlParameter.Optional,
      week = UrlParameter.Optional
  },
  new { teamID = @"\d+" });
于 2012-10-17T21:25:42.553 回答