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

相关文章

引言 本文从Linux小白的视角, 在CentOS 7.x服务器上搭建一个...
引言: 多线程编程/异步编程非常复杂,有很多概念和工具需要...
一. 宏观概念 ASP.NET Core Middleware是在应用程序处理管道...
背景 在.Net和C#中运行异步代码相当简单,因为我们有时候需要...
HTTP基本认证 在HTTP中,HTTP基本认证(Basic Authenticatio...
1.Linq 执行多列排序 OrderBy的意义是按照指定顺序排序,连续...