如何在 ASP.Net Core 中使用條件中間件
ASP.Net Core 是微軟開源的跨平臺、可擴展、輕量級的模塊化框架,可用于構建高性能的web應用程序。中間件組件可以注入到 ASP.Net Core 請求管道中實現對 Request 和 Response 的定制和修改。
ASP.Net Core 中間件可以用于檢查、路由或者修改流轉于Pipeline的Request和Response。本文將會討論如何使用這些中間件來實現一些高級操作。
Use,Run,Map方法
介紹Use、Map,Run方法常用來一起構建 HTTP Pipeline 管道,下面快速瀏覽一下這些方法和它們的用途。
- Use
該方法將會執行一個委托,然后將 交接棒 傳給Pipeline的下一個中間件,因該方法短暫擁有交接棒,所以該方法可用于 短路操作。
- Run
該方法會執行委托并返回結果。
- Map
該方法將有條件地執行委托并返回結果。
注冊中間件
中間件是在 Startup.Configure 中進行注冊,調用方法就是 Use*系列擴展方法,下面是注冊中間件的語法。
- public void Configure(IApplicationBuilder app, IHostingEnvironment env)
- {
- app.UseMyCustomMiddleware<MyCustomMiddleware>();
- }
需要注意的是,中間件的執行順序和你注冊的順序是保持一致的。
Invoke 方法
每個中間件都包含一個 Invoke() 方法, 這個方法參數是 HttpContext 的一個實例,本中間件的業務邏輯會在下一個中間件的執行前后都會被執行,如果你有點懵的話,可以了解一下什么叫:遞歸調用,如下面代碼注釋所示:
- 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
- }
分流 Http 管道
Map系擴展方法,比如:Map 和 MapWhen,它們常用于給 pipeline 管道操作進行分流,前者是基于 Request path 進行分流,后者是基于指定的 謂語動詞 進行分流。
下面的代碼片段展示了如何使用 Map 方法對 Request Pipeline 進行分流。
- 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<HttpContext, bool> predicate
- delegate action
你可以在 Startup.Configure 方法中拒絕 text/xml 格式的 request,如下代碼所示:
- 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();
- }
使用 UseWhen
UseWhen方法可以用于有條件的執行中間件,下面的代碼片段展示了如果當前 Request 請求路徑是以 /api 開頭的話,執行一個指定的中間件,代碼如下:
- app.UseWhen(context => context.Request.Path.StartsWithSegments("/api"), applicationBuilder =>
- {
- applicationBuilder.UseCustomMiddleware();
- });
請注意,UseWhen 不像 MapWhen,前者會繼續執行后面的中間件邏輯,不管當前 UseWhen 的委托函數返回的是 true 還是 false,如果有點懵的話,可以理解一下下面的代碼:
- 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 有條件的執行中間件。
譯文鏈接:https://www.infoworld.com/article/3429602/how-to-use-conditional-middleware-in-aspnet-core.html