ASP.NET Core 5中.NET Framework MVC路由配置的等效实现咨询
ASP.NET Core 5 等效路由实现方案
直接在UseEndpoints配置块中添加如下代码即可,和你原有.NET Framework路由逻辑完全一致:
app.UseEndpoints(endpoints => { // 匹配 /actualidad 路径的自定义路由 endpoints.MapControllerRoute( name: "actualidad", pattern: "actualidad", defaults: new { controller = "seccion", action = "detalle", id = 2 }); // 你原有的其他路由,注意自定义路由要放在通用路由前面优先匹配 endpoints.MapControllerRoute( name: "historias", pattern: "{controller=Podcast}/{action=seccion}/{id=?}"); });
默认值设置的两种方式
- 固定路径路由(即pattern为固定字符串,没有动态占位符):直接通过
MapControllerRoute的defaults参数指定所有参数的默认值即可,支持自定义任意参数的默认值 - 带动态占位符的路由:除了用defaults参数,也可以直接在pattern的占位符中声明默认值,比如需要给historias路由的id设置默认值2,修改pattern为
"{controller=Podcast}/{action=seccion}/{id=2}"即可;如果要保留可选属性同时设置默认值,写法为"{controller=Podcast}/{action=seccion}/{id?=2}"
内容的提问来源于stack exchange,提问作者Daniel Lazarte
相关产品推荐
相关产品推荐

