ASP.NET Core端點(diǎn)路由中三種讓人困惑的路由函數(shù)


早先提及了端點(diǎn)路由app.UseEndpoints, 端點(diǎn)路由強(qiáng)調(diào)的是端點(diǎn)和路由,其核心目的是將請求落地點(diǎn)與路由尋址方式解耦。
這里面有幾個(gè)容易混淆的函數(shù)
?MapControllerRoute?MapDefaultControllerRoute?MapControllers
有什么不同?什么時(shí)候該用哪一個(gè)?
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項(xiàng)目中;
需要傳參name pattern defaults constraints dataTokens;
你可以在項(xiàng)目中這樣寫:
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項(xiàng)目的早期寫法,讓用戶請求的url去匹配開發(fā)者的Controller-Action名稱。
如今約定路由并不是主流,因?yàn)樗^的約定路由對于用戶瀏覽并不友好,而且暴露了后端開發(fā)者定義的瑣碎的Controller、Action名稱。
實(shí)際上,不應(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項(xiàng)目中。
全文梳理就會(huì)發(fā)現(xiàn): 官方英文描述屢次出現(xiàn)的route,其實(shí)特指的是約定路由。
這樣的描述我其實(shí)是不茍同的:
路由在.NET里面, 已經(jīng)被普世認(rèn)定為“約定路由”和“特性路由”,基于這種認(rèn)知,我讀了好幾遍官方英文描述,其實(shí)沒讀出個(gè)所以然的。
官方英文描述使用 “route”來特指“約定路由”會(huì)誤導(dǎo)開發(fā)者。
https://github.com/dotnet/aspnetcore/blob/main/src/Mvc/Mvc.Core/src/Builder/ControllerEndpointRouteBuilderExtensions.cs
【推薦】.NET Core開發(fā)實(shí)戰(zhàn)視頻課程 ★★★
.NET Core實(shí)戰(zhàn)項(xiàng)目之CMS 第一章 入門篇-開篇及總體規(guī)劃
【.NET Core微服務(wù)實(shí)戰(zhàn)-統(tǒng)一身份認(rèn)證】開篇及目錄索引
Redis基本使用及百億數(shù)據(jù)量中的使用技巧分享(附視頻地址及觀看指南)
.NET Core中的一個(gè)接口多種實(shí)現(xiàn)的依賴注入與動(dòng)態(tài)選擇看這篇就夠了
10個(gè)小技巧助您寫出高性能的ASP.NET Core代碼
用abp vNext快速開發(fā)Quartz.NET定時(shí)任務(wù)管理界面
在ASP.NET Core中創(chuàng)建基于Quartz.NET托管服務(wù)輕松實(shí)現(xiàn)作業(yè)調(diào)度
現(xiàn)身說法:實(shí)際業(yè)務(wù)出發(fā)分析百億數(shù)據(jù)量下的多表查詢優(yōu)化
