ASP.NET Core端點路由中三種讓人困惑的路由函數(shù)
早先提及了端點路由app.UseEndpoints, 端點路由強(qiáng)調(diào)的是端點和路由,其核心目的是將請求落地點與路由尋址方式解耦。
《ASP.NET Core端點路由作用原理》
這里面有幾個容易混淆的函數(shù)
- 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名稱,默認(rèn)命中home/index 方法體。
說到底這種寫法:
是MVC web項目的早期寫法,讓用戶請求的url去匹配開發(fā)者的Controller-Action名稱。
如今約定路由并不是主流,因為所謂的約定路由對于用戶瀏覽并不友好,而且暴露了后端開發(fā)者定義的瑣碎的Controller、Action名稱。
實際上,不應(yīng)該讓用戶的url去匹配開發(fā)者定義的Controller-Action名稱(太丑陋的行為),而應(yīng)該讓開發(fā)者去匹配用戶想要使用的url, 這樣特性路由出現(xiàn)了。
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(); 正是上面約定路由的默認(rèn)樣例,這沒什么好聊的。
3. MapControllers
Adds endpoints for controller actions to the Microsoft.AspNetCore.Routing.IEndpointRouteBuilder without specifying any routes.
不對約定路由做任何假設(shè),也就是不使用約定路由,依賴用戶的特性路由, 一般用在WebAPI項目中。
全文梳理就會發(fā)現(xiàn): 官方英文描述屢次出現(xiàn)的route,其實特指的是約定路由。
這樣的描述我其實是不茍同的:
路由在.NET里面, 已經(jīng)被普世認(rèn)定為“約定路由”和“特性路由”,基于這種認(rèn)知,我讀了好幾遍官方英文描述,其實沒讀出個所以然的。
官方英文描述使用 “route”來特指“約定路由”會誤導(dǎo)開發(fā)者。
https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Builder/ControllerEndpointRouteBuilderExtensions.cs