如何使用ASP.Net Core中的條件中間件?
譯文
【51CTO.com快譯】ASP.Net Core是微軟的一種開源跨平臺框架,具有可擴展、精簡化和模塊化的優點,可用于構建高性能Web應用程序。中間件組件可以用在ASP.Net Core請求管道中,定制處理請求和響應的方式。
ASP.Net Core中間件組件還可用于檢查、路由或修改流經管道的請求和響應消息。本文討論了如何用ASP.Net Core中的中間件執行一些高級操作。
創建ASP.Net Core MVC項目
首先,不妨在Visual Studio中創建一個ASP.Net Core項目。假設你的系統中已安裝Visual Studio 2017或Visual Studio 2019,按照下列步驟,在Visual Studio中創建一個新的ASP.Net Core項目。
- 啟動Visual Studio IDE。
- 點擊“創建新項目”。
- 在“創建新項目”窗口中,從顯示的模板列表中選擇“ASP.Net Core Web應用程序”。
- 點擊“下一步”。
- 在“配置新項目”窗口中,指定新項目的名稱和位置。
- 點擊“創建”。
- 在接下來顯示的“創建新的ASP.Net Core Web應用程序”中,從頂部的下拉列表中選擇.Net Core作為運行時環境和ASP.Net Core 2.2(或更高版本)。
- 選擇“Web應用程序(模型-視圖-控制器)”作為項目模板,創建一個新的ASP.Net Core應用程序。
- 確保“啟用Docker支持”和“針對HTTPS的配置”復選框未勾選,因為我們在此處不會使用那些功能。
- 確保身份驗證設置為“無身份驗證”,因為我們也不會使用身份驗證。
- 點擊“創建”。
遵循這些步驟應該可以在Visual Studio中創建一個新的ASP.Net Core項目。我們將在本文的后續部分中使用該項目。
ASP.Net Core中的Use、Run和Map等方法
Use、Map和Run等方法用于在ASP.Net Core中配置HTTP管道。下面簡要介紹這每個方法及用途。
- Use——該方法將執行委托(delegate),然后進入到管道中的下一步。Use方法還可用于使管道短路。
- Run——該方法將執行委托并返回結果。
- Map——該方法將有條件地執行委托并返回結果。
ASP.Net Core中注冊中間件
ASP.Net Core中的中間件組件在Startup類的Configure方法中注冊。Use *擴展方法用于注冊中間件。下面是注冊中間件組件的語法。
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- app.UseMyCustomMiddleware();
- }
值得一提的是,中間件組件按它們注冊的順序來加以執行。
ASP.Net Core中的Invoke方法
每個中間件組件都包含一個Invoke方法。該方法接受對HttpContext實例的引用作為實參。中間件組件可以在調用下一個中間件組件前后執行操作。下面是典型的Invoke方法的示例:
- public async Task Invoke(HttpContext context)
- {
- // Write code here that will be executed before the
- // next middleware is called
- await _next.Invoke(context); // call next middleware
- // Write code here that will be executed after the
- //next middleware is called
- }
ASP.Net Core中使HTTP管道分支
Map擴展方法(即Map和MapWhen)用于使管道分支。Map用于基于特定的請求路徑來分支,而MapWhen用于基于特定斷言的結果來分支。
下列代碼片段表明了Map方法如何用于使請求管道分支。
- public class Startup
- {
- private static void MapRequestA(IApplicationBuilder app)
- {
- app.Run(async context =>
- {
- await context.Response.WriteAsync("This is MapRequestA");
- });
- }
- private static void MapRequestB(IApplicationBuilder app)
- {
- app.Run(async context =>
- {
- await context.Response.WriteAsync("This is MapRequestB");
- });
- }
- private static void MapRequestC(IApplicationBuilder app)
- {
- app.Run(async context =>
- {
- await context.Response.WriteAsync("This is MapRequestC");
- });
- }
- public void Configure(IApplicationBuilder app)
- {
- app.Map("/mapRequestPathA", MapRequestA);
- app.Map("/mapRequestPathB", MapRequestB);
- app.Map("/mapRequestPathB", MapRequestC);
- app.Run(async context =>
- {
- await context.Response.WriteAsync("Hello World!");
- });
- }
- //Other methods
- }
MapWhen方法接受兩個參數:
- Func
- 委托操作
你可以在Startup類的Configure方法中使用下列代碼片段,不允許內容類型“text/html”。
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- }
- app.MapWhen(context => context.Request.ContentType.Equals
- ("text/xml", StringComparison.InvariantCultureIgnoreCase),
- (IApplicationBuilder applicationBuilder) =>
- {
- applicationBuilder.Run(async context =>
- {
- await Task.FromResult(context.Response.StatusCode = StatusCodes.Status406NotAcceptable);
- });
- });
- app.UseMvc();
- }
ASP.Net Core中的UseWhen方法
UseWhen方法可用于有條件地執行中間件。下列代碼片段表明了如果請求路徑以“/api”開頭,UseWhen方法如何用于執行中間件組件。
- app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), applicationBuilder =>
- {
- applicationBuilder.UseCustomMiddleware();
- });
請注意:與MapWhen不同,UseWhen方法繼續執行后一個中間件,不管UseWhen斷言是真還是假。不妨通過示例了解這一點??紤]下面這部分代碼:
- app.UseMiddlewareA();
- app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), applicationBuilder =>
- {
- applicationBuilder.UseMiddlewareB();
- });
- app.UseMiddlewareC();
如果中間件沒有短路,中間件A和C將始終執行。只有請求路徑以“/api”開關,中間件B才會執行。
在ASP.Net Core中,請求處理管道中有一連串中間件組件。所有請求和響應都流經該管道。新請求進入后,這些中間件組件或處理請求,或將請求傳遞到管道中的下一個組件。想完成更復雜的請求處理,我們可以使用Map和MapWhen方法使管道分支,使用UseWhen有條件地執行中間件。
【51CTO譯稿,合作站點轉載請注明原文譯者和出處為51CTO.com】