Asp.net mvc .net mvc路由默认控制器/操作,但不是默认参数
我创建了这条路线Asp.net mvc .net mvc路由默认控制器/操作,但不是默认参数,asp.net-mvc,asp.net-mvc-4,asp.net-mvc-routing,mvcroutehandler,Asp.net Mvc,Asp.net Mvc 4,Asp.net Mvc Routing,Mvcroutehandler,我创建了这条路线 routes.MapRoute( name: "Survey", url: "{controller}/{action}/{surveyid}/{userid}/{hash}", defaults: new { controller = "Home", action = "Survey" }, constraints: ne
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强制它,但我认为它应该自动选择这一个。路由管理员并不知道如果你说/1/1/3r2ytg,1代表调查ID,另1代表用户ID等。
它只知道一个路径(localhost:3086)和x数量的“文件夹”
因此,如果您调用
http://localhost:3086/1/1/3r2ytg
他将1映射到控制器,1映射到操作,3r2ytg映射到测量ID。它找不到userId或hash,因为没有指定默认值,所以他找不到路由。
第一条路由中的默认值没有意义,因为它们永远不会触发。
默认值应该在url的末尾,这有点道理。您需要为每个组合创建路由 选中此项
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+" }
);
选中此项如果需要,请小心不要替换默认控制器/操作/id流。尽管问题得到了回答,但我还是用直接跟进的方式更新了我的帖子,这很有意思