ASP.NET Core端点路由中三种让人困惑的路由函数

早先提及了端点路由app.UseEndpoints, 端点路由强调的是端点路由,其核心目的是将 请求落地点与路由寻址方式解耦。

这里面有几个容易混淆的函数

  • MapControllerRoute
  • MapDefaultControllerRoute
  • MapControllers

有什么不同?什么时候该用哪一个?


MapControllerRoute

Adds endpoints for controller actions to the Microsoft.AspNetCore.Routing.IEndpointRouteBuilder
and specifies a route with the given name, pattern, defaults, constraints, and dataTokens.

url约定路由(conventional routing), 通常用在MVC项目中;

需要传参name pattern defaults constraints dataTokens;

你可以在项目中这样写:

endpoints.MapControllerRoute(
name:"default",
pattern:"{controller=Home}/{action=index}/{id?}"
);

如果请求url满足 {host}{controller_name}{action_name}{option_id},将命中Controller=controller_name Action=action_name的方法体;
如果你不提供controller、action名称,默认是home/index.

说到底这种写法:
是MVC web项目的早期写法,让用户请求的url去匹配开发者的Controller-Action名称。

如今约定路由并不是主流,因为所谓的约定路由对于用户浏览并不友好,而且暴露了后端开发者定义的琐碎的Controller、Action名称。

实际上,不应该让用户的url去匹配开发者定义的Controller-Action名称(太丑陋的行为),而应该让开发者去匹配用户想要使用的url, 这样特性路由出现了

MapDefaultControllerRoute

Adds endpoints for controller actions to the Microsoft.AspNetCore.Routing.IEndpointRouteBuilder and adds the default route {controller=Home}/{action=Index}/{id?}.

endpoints.MapDefaultControllerRoute(); 正是上面约定路由的默认样例,这没什么好聊的。

MapControllers

Adds endpoints for controller actions to the Microsoft.AspNetCore.Routing.IEndpointRouteBuilder without specifying any routes.

不对约定路由做任何假设,也就是不使用约定路由,依赖用户的特性路由, 一般用在WebAPI项目中。


全文梳理就会发现: 官方英文描述屡次出现的route,其实特指的是约定路由。

这样的描述我其实是不苟同的:

路由在.NET里面, 已经被普世认定为“约定路由”和“特性路由”,基于这种认知,我读了好几遍官方英文描述,其实没读出个所以然的。

官方英文描述使用 “route”来特指“约定路由”会误导开发者。

https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Builder/ControllerEndpointRouteBuilderExtensions.cs

https://github.com/dotnet/aspnetcore/issues/36279

posted @   码甲哥不卷  阅读(2871)  评论(4编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示

目录导航