ASP.NET Core端點路由中三種讓人困惑的路由函數
早先提及了端點路由app.UseEndpoints, 端點路由強調的是端點和路由,其核心目的是將請求落地點與路由尋址方式解耦。
《ASP.NET Core端點路由作用原理》
這里面有幾個容易混淆的函數
- MapControllerRoute
- MapDefaultControllerRoute
- MapControllers
有什么不同?什么時候該用哪一個?
1. 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.
約定路由(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的方法體;如果url不提供controller、action名稱,默認命中home/index 方法體。
說到底這種寫法:
是MVC web項目的早期寫法,讓用戶請求的url去匹配開發者的Controller-Action名稱。
如今約定路由并不是主流,因為所謂的約定路由對于用戶瀏覽并不友好,而且暴露了后端開發者定義的瑣碎的Controller、Action名稱。
實際上,不應該讓用戶的url去匹配開發者定義的Controller-Action名稱(太丑陋的行為),而應該讓開發者去匹配用戶想要使用的url, 這樣特性路由出現了。
2. MapDefaultControllerRoute
Adds endpoints for controller actions to the Microsoft.AspNetCore.Routing.IEndpointRouteBuilder and adds the default route {controller=Home}/{action=Index}/{id?}.
endpoints.MapDefaultControllerRoute(); 正是上面約定路由的默認樣例,這沒什么好聊的。
3. 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