无参数Index Action响应带参数URL请求的路由问题排查
这确实是路由配置在背后起作用,我来给你拆解清楚原因和解决办法:
首先,你的路由配置里应该包含了ASP.NET MVC默认的路由规则(从你给出的代码片段来看,大概率是这样),默认路由的结构大概是这样的:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
这里的关键是id = UrlParameter.Optional——它表示id这个路由参数是可选的,也就是说:
- 当你访问
/Home/Index时,路由系统会匹配到Home控制器的Index方法; - 当你访问
/Home/Index/example时,路由系统会把example解析为id参数的值,但因为你的Index方法并没有声明接收id参数,MVC并不会因此拒绝匹配,它只会检查是否存在名称为Index的Action,而不会强制要求Action必须接收所有路由中定义的参数。所以你的Index方法依然会被执行。
接下来给你几种解决这个问题的方案,你可以根据自己的需求选择:
方案1:添加更严格的前置路由
在默认路由之前,专门添加一个匹配Home/Index的路由,这样当访问Home/Index/example时,会跳过这个严格路由,走默认路由,但如果你的Index方法没有接收id参数,这类请求会返回404:
routes.MapRoute( name: "HomeIndexExact", url: "Home/Index", defaults: new { controller = "Home", action = "Index" } ); // 原来的默认路由放在后面 routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } );
方案2:使用属性路由约束
给你的Index Action添加[Route]属性,明确指定它只能匹配精确的URL:
[Route("Home/Index")] public ActionResult Index() { // ...你的代码 return View(); }
这样只有严格访问/Home/Index时才会触发这个Action,/Home/Index/example这类请求会直接返回404。
方案3:给默认路由添加参数约束
如果你的其他Action需要id参数(比如详情页),可以给默认路由的id添加约束,比如只允许数字:
routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, constraints: new { id = @"\d+" } // 约束id必须是数字 );
这样当你访问/Home/Index/example时,因为example不是数字,默认路由不会匹配,最终会返回404。
内容的提问来源于stack exchange,提问作者Ege Bayrak
相关产品推荐
相关产品推荐

