詳解如何在ASP.NET Core中使用Route特性
ASP.NET Core 中的 Route 中間件的職責(zé)在于將 request 匹配到各自 Route 處理程序上,Route 分兩種:基于約定 和 基本特性 模式。
基于約定 模式的Route采用集中化的方式,而 基于特性 的方式允許你在 Action 或者 Controller 上單獨(dú)定義,到底采用哪一種可以基于你自己的應(yīng)用場(chǎng)景,本篇就來(lái)討論如何使用 基于特性 模式。
創(chuàng)建 Controller 類
創(chuàng)建一個(gè) DefaultController 類,新增如下代碼。
public class DefaultController : Controller { [Route("")] [Route("Default")] [Route("Default/Index")] public ActionResult Index() { return new EmptyResult(); } [Route("Default/GetRecordsById/{id}")] public ActionResult GetRecordsById(int id) { string str = string.Format ("The id passed as parameter is: {0}", id); return Ok(str); } }
Controller 級(jí)別定義 Route 特性
Route特性可用于 Controller 和 Action 級(jí)別,值得注意的是,如果應(yīng)到到前者,那么 Controller 下的所有 Action 都受這個(gè) Route 管控。
如果你仔細(xì)觀察上面的 DefaultController 類代碼,你會(huì)發(fā)現(xiàn)兩個(gè) Action 方法的 Route 路徑都有 Default 前綴,這就不優(yōu)雅了,優(yōu)化方式就是把 Route 路徑中的 Default 提取到 Controller 級(jí)別,代碼如下:
[Route("Default")] public class DefaultController : Controller { [Route("")] [Route("Index")] public ActionResult Index() { return new EmptyResult(); } [HttpGet] [Route("GetRecordsById/{id}")] public ActionResult GetRecordsById(int id) { string str = string.Format("The id passed as parameter is: {0}", id); return Ok(str); } }
可以看出當(dāng) Controller 和 Action 級(jí)別都被 Route 打上標(biāo)記之后,Asp.Net Core 中的 Route 引擎會(huì)自動(dòng)將兩者拼接起來(lái),當(dāng)然更簡(jiǎn)單粗暴的做法就是在 Controller 上使用 RoutePrefix 特性,如下代碼所示:
[RoutePrefix("services")] public class HomeController : Controller { //Action methods }
Action 級(jí)別定義 Route 特性
參考剛才的 DefaultController 類,我在 Index 方法上面定義了三個(gè) Route 特性,這就意味著下面三種 Route 都可以訪問(wèn)到 Index() 方法,如下代碼所示:
http://localhost:11277
http://localhost:11277/home
http://localhost:11277/home/index
常常在 基于約定 模式的Route中,它的 Route template 會(huì)有一些對(duì)參數(shù)的約定,比如下面的代碼:
app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); });
同樣 基于特性 模式的 Route 也是可以使用參數(shù)模式的,比如文章之前的 DefaultController.GetRecordsById 就是的,值得注意的是模板中的 {id} 表示可接收任何參數(shù),如 string,int 等等,如果你想限定為 int 的話,也是可以實(shí)現(xiàn)的。
使用 Route 約束
Route 約束 就是 Controller 前的一個(gè)防火墻,他會(huì)踢掉一些不合規(guī)范的 Action 請(qǐng)求,比如說(shuō):你要求某個(gè) Action 接收的參數(shù)必須是 int,那在 Route 模板中定義的語(yǔ)法格式一定是這樣的 {parameter:constraint},如下代碼所示:
[Route("Default/GetRecordsById/{id:int}")] public ActionResult GetRecordsById(int id) { string str = string.Format("The id passed as parameter is: {0}", id); return Ok(str); }
在 Route 中使用可選參數(shù)
你也可以在 Route Template 上指定可選參數(shù),意味著這個(gè)參數(shù)可傳可不傳,格式如下:
[Route("Sales/GetSalesByRegionId/{id?}")]
有一點(diǎn)非常重要,當(dāng)你使用了 Route特性 之后,其實(shí) Controller 或者 Action 的名字就不再重要了,因?yàn)?Route處理引擎 已經(jīng)不再將其作為參考選項(xiàng),下面的代碼片段展示了如何在 Action 方法上變更 Route template 格式。
[Route("Home/GetRecordsById/{id:int}")] public ActionResult GetRecordsById(int id) { string str = string.Format("The id passed as parameter is: {0}", id); return Ok(str); }
接下來(lái)可以直接使用如下地址訪問(wèn) GetRecordsById 方法。
http://localhost:11277/home/GetRecordsById/1
對(duì) Action 中的參數(shù)使用多個(gè)約束
真實(shí)場(chǎng)景中你不僅要求 id 必須是整數(shù),還要求必須有一定意義,比如說(shuō)最小值為1,對(duì)這種有 多重約束 的需求如何去實(shí)現(xiàn)呢? 請(qǐng)看下面代碼。
[Route("Default/GetRecordsById/{id:int:min(1)}")] public ActionResult GetRecordsById(int id) { string str = string.Format("The id passed as parameter is: {0}", id); return Ok(str); }
常使用的 Route 約束
- int 限定為 int 類型
- max/min 限定 int 的最大數(shù)和最小數(shù)
- minlength 限定 string 的最小長(zhǎng)度
- regex 限定符合的正則
創(chuàng)建自定義的 Route 約束
如果上面的一些約束不滿足你的要求,你完全可以為你的場(chǎng)景深度定制,做法就是使用 IRouteConstraint 接口并實(shí)現(xiàn)它的 Match 方法即可,如下代碼所示:
public class CustomRouteConstraint : IRouteConstraint { public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { throw new NotImplementedException(); } }
在 Controller 上使用 token 占位符
所謂的 token 占位符 就是具有一些特定含義的占位符號(hào),比如說(shuō):[action], [area] 和 [controller],分別表示用你真實(shí)的 Controller 和 Action 去替換,下面的代碼展示了如何使用這種模式去實(shí)現(xiàn)。
[Route("[controller]/[action]")] public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } //Other action methods }
整體來(lái)看,基于特性 的 Route 給了你更多的操控權(quán)限,靈活的 Route Template 配置實(shí)現(xiàn)了 Controller 和 Action 的解耦,當(dāng)然這里也不是說(shuō) 基于約定 的Route 不好,畢竟人家是 Global 級(jí)別的,真實(shí)場(chǎng)景下兩者更多的是混著用。
譯文鏈接:https://www.infoworld.com/article/3569369/how-to-use-attribute-routing-in-aspnet-core.html
到此這篇關(guān)于如何在ASP.NET Core中使用Route特性的文章就介紹到這了,更多相關(guān)ASP.NET Core Route特性內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 在 ASP.Net Core 中使用 MiniProfiler的方法
- ASP.NET Core MVC解決控制器同名Action請(qǐng)求不明確的問(wèn)題
- Asp.Net Core 調(diào)用第三方Open API查詢物流數(shù)據(jù)的示例
- Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫(kù)的步驟
- 如何在Asp.Net Core中集成Refit
- ASP.NET Core WebApi版本控制的實(shí)現(xiàn)
- ASP.NET Core對(duì)不同類型的用戶進(jìn)行區(qū)別限流詳解
- 詳解如何在ASP.NET Core中編寫(xiě)高效的控制器
- 詳解如何在ASP.NET Core中使用IHttpClientFactory
- ASP.NET Core 使用Cookie驗(yàn)證身份的示例代碼
- 如何在ASP.Net Core使用分布式緩存的實(shí)現(xiàn)
- ASP.NET Core中的配置詳解
- 詳解如何在ASP.NET Core Web API中以三種方式返回?cái)?shù)據(jù)
- 如何在Asp.Net Core中集成ABP Dapper
相關(guān)文章
.Net?Api?中使用Elasticsearch存儲(chǔ)文檔的方法
Elasticsearch 是一個(gè)分布式、高擴(kuò)展、高實(shí)時(shí)的搜索與數(shù)據(jù)分析引擎,在C# 的環(huán)境中,有一個(gè)Es的官方拓展包Nest,可以讓我們方便快捷的使用上Es數(shù)據(jù)庫(kù),本文重點(diǎn)給大家介紹.Net?Api?中使用Elasticsearch存儲(chǔ)文檔的方法,感興趣的朋友一起看看吧2022-01-01ASP.NET中Webservice安全 實(shí)現(xiàn)訪問(wèn)權(quán)限控制
本文主要講解ASP.NET中的Webservice的安全設(shè)置兩種方法,一種基于soapheader,一種基于SoapExtensionAttribute,需要的朋友可以參考下。2016-05-05asp.net輸出重寫(xiě)壓縮頁(yè)面文件實(shí)例代碼
這篇文章主要介紹了asp.net輸出重寫(xiě)壓縮頁(yè)面文件實(shí)例代碼,需要的朋友可以參考下2014-02-02asp.net mvc 從數(shù)據(jù)庫(kù)中讀取圖片的實(shí)現(xiàn)代碼
今天搞了一天的MVC,在顯示圖片的時(shí)候老是出現(xiàn)問(wèn)題,從網(wǎng)上搜索了好久,才找到解決方法。2010-05-05ASP.NET Core中使用MialKit實(shí)現(xiàn)郵件發(fā)送功能
這篇文章主要介紹了ASP.NET Core中使用MialKit實(shí)現(xiàn)郵件發(fā)送功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-10-10asp.net 動(dòng)態(tài)生成rdlc報(bào)表(原創(chuàng))
因?yàn)楣拘枨?研究微軟的Reportviewer 因?yàn)橛性S多特別要求所以動(dòng)態(tài)調(diào)用 比較靈活 我的需求是 根據(jù)數(shù)據(jù)不同的合并表頭 (參考了隨心所欲的博客文檔 再次表示感謝)2011-12-12.NET8.0發(fā)布到IIS的實(shí)現(xiàn)步驟
很多學(xué)習(xí).Net的朋友初次接觸并不知道一個(gè).Net應(yīng)用怎么發(fā)布到IIS服務(wù)器中去,本文主要介紹了.NET8.0發(fā)布到IIS的實(shí)現(xiàn)步驟,感興趣的可以了解一下2024-05-05