You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置MapControllerRoute以支持多级URL的分类页面路由?

问题描述

需要重写分类URL,使其指向指定视图/控制器,要求支持任意层级的URL格式,例如:

  • /ladies/shoes/cat/12345
  • /Ladies/shoes/sports-shoes/cat/1233

当前路由配置如下:

app.MapControllerRoute(name: "CategoryPage", pattern: "shop/{productName}/Cat/{id}", defaults: new { area = "shop", controller = "Category", action = "index" });

控制器仅需末尾的id参数,URL中的分类路径仅用于展示,无需传递给控制器,请问如何修改路由配置以支持多级路径?

控制器代码:

public async Task<IActionResult> Index(long id)
解决方案

要支持任意层级的前置路径,只需在路由模式中使用catch-all参数(语法为{*parameterName}),它会匹配该位置之后的所有剩余路径片段。

修改后的路由配置如下:

app.MapControllerRoute(
    name: "CategoryPage",
    pattern: "{*productName}/Cat/{id}",
    defaults: new { area = "shop", controller = "Category", action = "index" }
);

关键说明:

  • {*productName}会捕获/Cat/{id}之前的所有路径内容,不管层级多少(比如ladies/shoes或Ladies/shoes/sports-shoes都能匹配)
  • 由于控制器的Index方法仅接收id参数,路由捕获的productName不会参与参数绑定,完全不影响控制器逻辑,仅作为URL展示用
  • 注意路由优先级:建议将这条路由放在其他更具体的路由之后,避免干扰正常的路由匹配

内容的提问来源于stack exchange,提问作者James Andrew Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:35:15