如果業務邏輯比較簡單的話,一條主管道就夠了,確實用不到分支管道。不過當業務邏輯比較複雜的時候,有時候我們可能希望根據情況的不同使用特殊的一組中間件來處理 HttpContext。這種情況下如果只用一條管道,處理起來會非常麻煩和混亂。此時就可以使用 Map/MapWhen/UseWhen 建立一個分支 ...
如果業務邏輯比較簡單的話,一條主管道就夠了,確實用不到分支管道。不過當業務邏輯比較複雜的時候,有時候我們可能希望根據情況的不同使用特殊的一組中間件來處理 HttpContext。這種情況下如果只用一條管道,處理起來會非常麻煩和混亂。此時就可以使用 Map/MapWhen/UseWhen 建立一個分支管道,當條件符合我們的設定時,由這個分支管道來處理 HttpContext。使用 Map/MapWhen/UseWhen 添加分支管道是很容易的,只要提供合適跳轉到分支管道的判斷邏輯,以及分支管道的構建方法就可以了。
一、對中間件管道進行分支
廢話不多說,我們直接通過一個Demo來看一下如何對中間件管道進行分支,如下:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using NETCoreMiddleware.Middlewares; namespace NETCoreMiddleware { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } //服務註冊(往容器中添加服務) // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } /// <summary> /// 配置Http請求處理管道 /// Http請求管道模型---就是Http請求被處理的步驟 /// 所謂管道,就是拿著HttpContext,經過多個步驟的加工,生成Response,這就是管道 /// </summary> /// <param name="app"></param> /// <param name="env"></param> // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { #region 環境參數 if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } #endregion 環境參數 //靜態文件中間件 app.UseStaticFiles(); #region 創建管道分支 //Map管道分支 app.Map("/map1", HandleMapTest1); app.Map("/map2", HandleMapTest2); //MapWhen管道分支 app.MapWhen(context => context.Request.Query.ContainsKey("mapwhen"), HandleBranch); //UseWhen管道分支 //UseWhen 與 MapWhen 不同的是,如果這個分支不發生短路或包含終端中間件,則會重新加入主管道 app.UseWhen(context => context.Request.Query.ContainsKey("usewhen"), HandleBranchAndRejoin); #endregion 創建管道分支 #region Use中間件 //中間件1 app.Use(next => { Console.WriteLine("middleware 1"); return async context => { await Task.Run(() => { Console.WriteLine(""); Console.WriteLine("===================================Middleware==================================="); Console.WriteLine($"This is middleware 1 Start"); }); await next.Invoke(context); await Task.Run(() => { Console.WriteLine($"This is middleware 1 End"); Console.WriteLine("===================================Middleware==================================="); }); }; }); //中間件2 app.Use(next => { Console.WriteLine("middleware 2"); return async context => { await Task.Run(() => Console.WriteLine($"This is middleware 2 Start")); await next.Invoke(context); //可通過不調用 next 參數使請求管道短路 await Task.Run(() => Console.WriteLine($"This is middleware 2 End")); }; }); //中間件3 app.Use(next => { Console.WriteLine("middleware 3"); return async context => { await Task.Run(() => Console.WriteLine($"This is middleware 3 Start")); await next.Invoke(context); await Task.Run(() => Console.WriteLine($"This is middleware 3 End")); }; }); //中間件4 //Use方法的另外一個重載 app.Use(async (context, next) => { await Task.Run(() => Console.WriteLine($"This is middleware 4 Start")); await next(); await Task.Run(() => Console.WriteLine($"This is middleware 4 End")); }); #endregion Use中間件 #region UseMiddleware中間件 app.UseMiddleware<CustomMiddleware>(); #endregion UseMiddleware中間件 #region 終端中間件 //app.Use(_ => handler); app.Run(async context => { await Task.Run(() => Console.WriteLine($"This is Run")); }); #endregion 終端中間件 #region 最終把請求交給MVC app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "areas", pattern: "{area:exists}/{controller=Home}/{action=Index}/{id?}"); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); #endregion 最終把請求交給MVC } #region 創建管道分支 /// <summary> /// Map管道分支1 /// </summary> /// <param name="app"></param> static void HandleMapTest1(IApplicationBuilder app) { //中間件 app.Use(next => { Console.WriteLine("HandleMapTest1"); return async context => { await Task.Run(() => { Console.WriteLine(""); Console.WriteLine($"This is HandleMapTest1 Start"); }); await next.Invoke(context); //可通過不調用 next 參數使請求管道短路 await Task.Run(() => Console.WriteLine($"This is HandleMapTest1 End")); }; }); } /// <summary> /// Map管道分支2 /// </summary> /// <param name="app"></param> static void HandleMapTest2(IApplicationBuilder app) { //中間件 app.Use(next => { Console.WriteLine("HandleMapTest2"); return async context => { await Task.Run(() => { Console.WriteLine(""); Console.WriteLine($"This is HandleMapTest2 Start"); }); await next.Invoke(context); //可通過不調用 next 參數使請求管道短路 await Task.Run(() => Console.WriteLine($"This is HandleMapTest2 End")); }; }); } /// <summary> /// MapWhen管道分支 /// </summary> /// <param name="app"></param> static void HandleBranch(IApplicationBuilder app) { //中間件 app.Use(next => { Console.WriteLine("HandleBranch"); return async context => { await Task.Run(() => { Console.WriteLine(""); Console.WriteLine($"This is HandleBranch Start"); }); await next.Invoke(context); //可通過不調用 next 參數使請求管道短路 await Task.Run(() => Console.WriteLine($"This is HandleBranch End")); }; }); } /// <summary> /// UseWhen管道分支 /// </summary> /// <param name="app"></param> static void HandleBranchAndRejoin(IApplicationBuilder app) { //中間件 app.Use(next => { Console.WriteLine("HandleBranchAndRejoin"); return async context => { await Task.Run(() => { Console.WriteLine(""); Console.WriteLine($"This is HandleBranchAndRejoin Start"); }); await next.Invoke(context); //可通過不調用 next 參數使請求管道短路 await Task.Run(() => Console.WriteLine($"This is HandleBranchAndRejoin End")); }; }); } #endregion 創建管道分支 } }
下麵我們使用命令行(CLI)方式啟動我們的網站,如下所示:
啟動成功後,我們來訪問一下 “http://localhost:5000/map1/” ,控制台輸出結果如下所示:
訪問 “http://localhost:5000/map2/” ,控制台輸出結果如下所示:
訪問 “http://localhost:5000/home/?mapwhen=1” ,控制台輸出結果如下所示:
訪問 “http://localhost:5000/home/?usewhen=1” ,控制台輸出結果如下所示:
Map 擴展用作約定來創建管道分支。 Map 基於給定請求路徑的匹配項來創建請求管道分支。 如果請求路徑以給定路徑開頭,則執行分支。
MapWhen 基於給定謂詞的結果創建請求管道分支。 Func<HttpContext, bool> 類型的任何謂詞均可用於將請求映射到管道的新分支。
UseWhen 也基於給定謂詞的結果創建請求管道分支。 與 MapWhen 不同的是,如果這個分支不發生短路或包含終端中間件,則會重新加入主管道。
二、中間件管道分支源碼解析
下麵我們結合ASP.NET Core源碼來分析下其實現原理:
1、Map擴展原理
我們將游標移動到 Map 處按 F12 轉到定義,如下所示:
可以發現它是位於 MapExtensions 擴展類中的,我們找到 MapExtensions 類的源碼,如下所示:
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Builder.Extensions; namespace Microsoft.AspNetCore.Builder { /// <summary> /// Extension methods for the <see cref="MapMiddleware"/>. /// </summary> public static class MapExtensions { /// <summary> /// Branches the request pipeline based on matches of the given request path. If the request path starts with /// the given path, the branch is executed. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param> /// <param name="pathMatch">The request path to match.</param> /// <param name="configuration">The branch to take for positive path matches.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns> public static IApplicationBuilder Map(this IApplicationBuilder app, PathString pathMatch, Action<IApplicationBuilder> configuration) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } if (pathMatch.HasValue && pathMatch.Value.EndsWith("/", StringComparison.Ordinal)) { throw new ArgumentException("The path must not end with a '/'", nameof(pathMatch)); } // create branch var branchBuilder = app.New(); configuration(branchBuilder); var branch = branchBuilder.Build(); var options = new MapOptions { Branch = branch, PathMatch = pathMatch, }; return app.Use(next => new MapMiddleware(next, options).Invoke); } } }
其中 ApplicationBuilder 類的源碼,如下所示:
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.Internal; namespace Microsoft.AspNetCore.Builder { public class ApplicationBuilder : IApplicationBuilder { private const string ServerFeaturesKey = "server.Features"; private const string ApplicationServicesKey = "application.Services"; private readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>(); public ApplicationBuilder(IServiceProvider serviceProvider) { Properties = new Dictionary<string, object>(StringComparer.Ordinal); ApplicationServices = serviceProvider; } public ApplicationBuilder(IServiceProvider serviceProvider, object server) : this(serviceProvider) { SetProperty(ServerFeaturesKey, server); } private ApplicationBuilder(ApplicationBuilder builder) { Properties = new CopyOnWriteDictionary<string, object>(builder.Properties, StringComparer.Ordinal); } public IServiceProvider ApplicationServices { get { return GetProperty<IServiceProvider>(ApplicationServicesKey); } set { SetProperty<IServiceProvider>(ApplicationServicesKey, value); } } public IFeatureCollection ServerFeatures { get { return GetProperty<IFeatureCollection>(ServerFeaturesKey); } } public IDictionary<string, object> Properties { get; } private T GetProperty<T>(string key) { object value; return Properties.TryGetValue(key, out value) ? (T)value : default(T); } private void SetProperty<T>(string key, T value) { Properties[key] = value; } public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware) { _components.Add(middleware); return this; } public IApplicationBuilder New() { return new ApplicationBuilder(this); } public RequestDelegate Build() { RequestDelegate app = context => { // If we reach the end of the pipeline, but we have an endpoint, then something unexpected has happened. // This could happen if user code sets an endpoint, but they forgot to add the UseEndpoint middleware. var endpoint = context.GetEndpoint(); var endpointRequestDelegate = endpoint?.RequestDelegate; if (endpointRequestDelegate != null) { var message = $"The request reached the end of the pipeline without executing the endpoint: '{endpoint.DisplayName}'. " + $"Please register the EndpointMiddleware using '{nameof(IApplicationBuilder)}.UseEndpoints(...)' if using " + $"routing."; throw new InvalidOperationException(message); } context.Response.StatusCode = 404; return Task.CompletedTask; }; foreach (var component in _components.Reverse()) { app = component(app); } return app; } } }Microsoft.AspNetCore.Builder.ApplicationBuilder類源碼
其中 MapMiddleware 類的源碼,如下所示:
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Builder.Extensions { /// <summary> /// Represents a middleware that maps a request path to a sub-request pipeline. /// </summary> public class MapMiddleware { private readonly RequestDelegate _next; private readonly MapOptions _options; /// <summary> /// Creates a new instance of <see cref="MapMiddleware"/>. /// </summary> /// <param name="next">The delegate representing the next middleware in the request pipeline.</param> /// <param name="options">The middleware options.</param> public MapMiddleware(RequestDelegate next, MapOptions options) { if (next == null) { throw new ArgumentNullException(nameof(next)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } _next = next; _options = options; } /// <summary> /// Executes the middleware. /// </summary> /// <param name="context">The <see cref="HttpContext"/> for the current request.</param> /// <returns>A task that represents the execution of this middleware.</returns> public async Task Invoke(HttpContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } PathString matchedPath; PathString remainingPath; if (context.Request.Path.StartsWithSegments(_options.PathMatch, out matchedPath, out remainingPath)) { // Update the path var path = context.Request.Path; var pathBase = context.Request.PathBase; context.Request.PathBase = pathBase.Add(matchedPath); context.Request.Path = remainingPath; try { await _options.Branch(context); } finally { context.Request.PathBase = pathBase; context.Request.Path = path; } } else { await _next(context); } } } }
在前兩篇文章中我們已經介紹過,中間件的註冊和管道的構建都是通過 ApplicationBuilder 進行的。因此要構建一個分支管道,需要一個新的 ApplicationBuilder ,並用它來註冊中間件,構建管道。為了在分支管道中也能夠共用我們在當前 ApplicationBuilder 中註冊的服務(或者說共用依賴註入容器,當然共用的並不止這些),在創建新的 ApplicationBuilder 時並不是直接 new 一個全新的,而是調用當前 ApplicationBuilder 的 New 方法在當前的基礎上創建新的,共用了當前 ApplicationBuilder 的 Properties(其中包含了依賴註入容器)。
在使用 Map 註冊中間件時我們會傳入一個 Action<IApplicationBuilder> 參數,它的作用就是當我們創建了新的 ApplicationBuilder 後,使用這個方法對其進行各種設置,最重要的就是在新的 ApplicationBuilder 上註冊分支管道的中間件。配置完成後調用分支 ApplicationBuilder 的 Build 方法構建管道,並把第一個中間件保存下來作為分支管道的入口。
在使用 Map 註冊中間件時傳入了一個 PathString 參數,PathString 對象我們可以簡單地認為是 string 。它用於記錄 HttpContext.HttpRequest.Path 中要匹配的區段(Segment)。這個字元串參數結尾不能是“/”。如果匹配成功則進入分支管道,匹配失則敗繼續當前管道。
新構建的管道和用於匹配的字元串保存為 MapOptions 對象,保存了 Map 規則和分支管道的入口。之後構建 MapMiddleware 對象,並把它的 Invoke 方法包裝為 RequestDelegate ,使用當前 ApplicationBuilder 的 Use 方法註冊中間件。
2、MapWhen擴展原理
我們將游標移動到 MapWhen 處按 F12 轉到定義,如下所示:
可以發現它是位於 MapWhenExtensions 擴展類中的,我們找到 MapWhenExtensions 類的源碼,如下所示:
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Builder.Extensions; namespace Microsoft.AspNetCore.Builder { using Predicate = Func<HttpContext, bool>; /// <summary> /// Extension methods for the <see cref="MapWhenMiddleware"/>. /// </summary> public static class MapWhenExtensions { /// <summary> /// Branches the request pipeline based on the result of the given predicate. /// </summary> /// <param name="app"></param> /// <param name="predicate">Invoked with the request environment to determine if the branch should be taken</param> /// <param name="configuration">Configures a branch to take</param> /// <returns></returns> public static IApplicationBuilder MapWhen(this IApplicationBuilder app, Predicate predicate, Action<IApplicationBuilder> configuration) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } // create branch var branchBuilder = app.New(); configuration(branchBuilder); var branch = branchBuilder.Build(); // put middleware in pipeline var options = new MapWhenOptions { Predicate = predicate, Branch = branch, }; return app.Use(next => new MapWhenMiddleware(next, options).Invoke); } } }
其中 MapWhenMiddleware 類的源碼,如下所示:
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Builder.Extensions { ///