4

我创造了这个路线.NET MVC路线默认的控制器/动作而不是默认参数

  routes.MapRoute( 
       name: "Survey", 
       url: "{controller}/{action}/{surveyid}/{userid}/{hash}", 
       defaults: new { controller = "Home", action = "Survey" }, 
       constraints: new { surveyid = @"\d+", userid = @"\d+" } 
      ); 

当我再浏览到

http://localhost:3086/Home/Survey/1/1/3r2ytg 

它的工作原理,但是如果我浏览到

http://localhost:3086/1/1/3r2ytg 

它不起作用。

如果我再变,像这样

 routes.MapRoute(
      name: "Survey", 
      url: "{surveyid}/{userid}/{hash}", 
      defaults: new { controller = "Home", action = "Survey" }, 
      constraints: new { surveyid = @"\d+", userid = @"\d+" } 
     ); 

完全相反会的工作路线(这是有道理的)。

但我很好奇第一条路线,我认为这两个网址应该工作,因为它应该抓住默认的控制器和行动,当没有给出。

更新

在我只有这个

 routes.MapRoute(
      name: "Survey", 
      url: "{surveyId}/{userId}/{hash}", 
      defaults: new { controller = "Home", action = "Survey" }, 
      constraints: new { surveyId = @"\d+", userId = @"\d+" } 
     ); 

为去年底是我想要的行为。然而,当我再调用

@Url.Action("Survey", "Home", new 
{ 
    userId = @Model.UserId, 
    surveyId = survey.Id, 
    hash = HashHelpers.CreateShortenedUrlSafeHash(@Model.SecretString + survey.Id.ToString() + @Model.UserId.ToString()) 
}) 

它产生

/Admin/Home/Survey?userId=25&surveyId=19&hash=2Norc 

,而不是一个闪亮的路径。我可以用Url.RouteUrl强制它,但我认为它应该自动选择这一个。

回答

3

您需要为每个组合创建路线。

入住这Phil Haack Article

routes.MapRoute( 
      name: "Survey", 
      url: "{controller}/{action}/{surveyid}/{userid}/{hash}", 
      defaults: new { controller = "Home", action = "Survey" }, 
      constraints: new { surveyid = @"\d+", userid = @"\d+" } 
); 

    routes.MapRoute(
     name: "Survey", 
     url: "{surveyid}/{userid}/{hash}", 
     defaults: new { controller = "Home", action = "Survey" }, 
     constraints: new { surveyid = @"\d+", userid = @"\d+" } 
); 

入住这Route with Two optional parameters in MVC3 not working

+0

要当心不要,如果你需要它替换默认的控制器/操作/ ID流动。如果不愿意使用这个。 – Kristof

+0

虽然这个问题得到了解答,我更新了我的帖子,并且直接跟进了一下, –

1

的routehandler并不真正知道,如果你说/ 1/1/3r2ytg 1是surveyId,另1对用户id等
它只是知道的路径(本地主机:3086)和x量“文件夹”
因此,如果您致电http://localhost:3086/1/1/3r2ytg,他会将1映射到控制器,1映射到action并将3r2ytg映射到surveyId。
它无法找到userId或散列,并且由于没有指定默认值,他无法找到路由。
您的第一条路线的默认值是毫无意义的,因为它们永远不会触发。
默认值应该在你的url的末尾,这是有道理的。