【问题标题】:.net mvc route default controller/action but not default parameters.net mvc 路由默认控制器/动作,但不是默认参数
【发布时间】:2013-10-11 08:45:02
【问题描述】:

我创建了这条路线

          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+" }
        );

正好相反会起作用(这是有道理的)。

但我对第一条路线感到好奇,我认为这两个 URL 都应该工作,因为它应该在没有给出默认控制器和操作时获取默认控制器和操作。

更新

最后我只选择了这个

        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 强制它,但我认为它应该自动选择这个。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing mvcroutehandler


    【解决方案1】:

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

    检查这个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

    【讨论】:

    • 如果需要,请注意不要替换默认的控制器/操作/id 流。如果不能随意使用它。
    • 尽管问题已得到解答,但我更新了我的帖子并直接跟进,这会很有趣
    【解决方案2】:

    路由处理程序并不真正知道,如果您说 /1/1/3r2ytg 1 用于surveyId,其他 1 用于 userId 等。
    它只知道一个路径 (localhost:3086) 和 x 个“文件夹”
    因此,如果您致电 http://localhost:3086/1/1/3r2ytg,他会将 1 映射到控制器,将 1 映射到操作,将 3r2ytg 映射到surveyId。
    它找不到 userId 或 hash,因为没有指定默认值,所以他找不到路由。
    第一条路由中的默认值是没有意义的,因为它们永远不会触发。
    默认值应该在你的 url 的末尾,这是有道理的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-01
      • 2016-10-07
      • 1970-01-01
      • 2014-01-11
      • 2012-08-14
      • 2011-07-15
      • 1970-01-01
      相关资源
      最近更新 更多