ASP.NET Core如何配置多可选路由参数实现斜杠分隔路径访问
问题原因
ASP.NET Core的路由匹配规则与ASP.NET MVC 4存在差异,你当前配置的路由存在两个核心问题:
- 路由模板中加入了
{action}占位符,意味着只有路径为/test/Index/参数1/参数2的格式才能命中路由,省略Index时无法匹配到TestController的Index方法 - 可选参数如果要通过路径传递,需要确保路由匹配顺序正确,且参数绑定来源可被路由系统识别
解决方案
方案1:固定参数数量适配
第一步:调整路由配置
将自定义路由放在全局路由规则的最前方(路由匹配按注册顺序优先级从高到低),移除模板中的{action}占位符,示例(.NET 6+ Program.cs):
// 自定义Test路由放在默认路由之前注册 app.MapControllerRoute( name: "TestController", pattern: "test/{id1?}/{id2?}/{id3?}/{id4?}/{id5?}/{id6?}/{id7?}/{id8?}/{id9?}/{id10?}/{id11?}/{id12?}", defaults: new { controller = "Test", action = "Index" }); // 原有默认路由放在后面 app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");
第二步:调整控制器参数绑定
给Action的参数添加[FromRoute]特性,强制从路由路径中读取参数,避免默认绑定优先读取查询参数:
[HttpGet] public IActionResult Index( [FromRoute] string id1 = null, [FromRoute] string id2 = null, [FromRoute] string id3 = null, [FromRoute] string id4 = null, [FromRoute] string id5 = null, [FromRoute] string id6 = null) { return Ok("hello world"); }
方案2:动态参数适配(更适合动态URL场景)
如果你的URL参数数量不固定,可以使用catch-all路由参数,无需提前定义12个可选参数,适配性更强:
路由配置修改为:
app.MapControllerRoute( name: "TestController", pattern: "test/{*allIds}", defaults: new { controller = "Test", action = "Index" });
控制器代码修改为:
[HttpGet] public IActionResult Index([FromRoute] string allIds = null) { // 按斜杠拆分获取所有路径参数,顺序和URL路径传递顺序一致 var idList = allIds?.Split('/', StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>(); // 按需从idList中取对应位置的参数即可,支持不限数量的路径参数 return Ok("hello world"); }
配置完成后即可通过/test/参数1/参数2/参数3的格式正常访问,无需将参数放在查询字符串中。
内容的提问来源于stack exchange,提问作者The Cookies Dog
相关产品推荐
相关产品推荐

