探究ASP.NET Core Middleware 實現
概念
ASP.NET Core Middleware是在應用程式處理管道pipeline中用於處理請求和操作響應的元件。
每個元件:
- 在pipeline中判斷是否將請求傳遞給下一個元件
- 在處理管道的下個元件執行之前和之後執行一些工作, HttpContxt物件能跨域請求、響應的執行週期
特性和行為
ASP.NET Core處理管道由一系列請求委託組成,一環接一環的被呼叫, 下面給出自己繪製的Middleware pipeline流程圖:
從上圖可以看出,請求自進入處理管道,經歷了四個中介軟體,每個中介軟體都包含後續緊鄰中介軟體 執行委託(next)的引用,同時每個中介軟體在交棒之前和交棒之後可以自行決定參與一些Http請求和響應的邏輯處理。
每個中介軟體還可以決定不將請求轉發給下一個委託,這稱為請求管道的短路(短路是有必要的,某些專有中介軟體比如 StaticFileMiddleware 可以在完成功能之後,避免請求被轉發到其他動態處理過程)。
原始碼實現
觀察一個標準的中介軟體程式碼的寫法和用法:
using System.Threading.Tasks; using Alyio.AspNetCore.ApiMessages; using Gridsum.WebDissector.Common; using Microsoft.AspNetCore.Http; namespace Gridsum.WebDissector { sealed class AuthorizationMiddleware { private readonly RequestDelegate _next;// 下一個中介軟體執行委託的引用 public AuthorizationMiddleware(RequestDelegate next) { _next = next; } public Task Invoke(HttpContext context)// 貫穿始終的HttpContext物件 { if (context.Request.Path.Value.StartsWith("/api/")) { return _next(context); } if (context.User.Identity.IsAuthenticated && context.User().DisallowBrowseWebsite) { throw new ForbiddenMessage("You are not allow to browse the website."); } return _next(context); } } } public static IApplicationBuilder UserAuthorization(this IApplicationBuilder app) { return app.UseMiddleware<AuthorizationMiddleware>(); } // 啟用該中介軟體,也就是註冊該中介軟體 app.UserAuthorization();
標準的中介軟體使用方式是如此簡單明瞭,帶著幾個問題探究一下原始碼實現
(1).中介軟體傳參是怎樣完成的: app.UseMiddleware<Authorization>(AuthOption); 我們傳參的時候,為什麼能自動注入中介軟體建構函式非第1個引數
(2).編寫中介軟體的時候,為什麼必須要定義特定的 Invoke/InvokeAsync 函式?
(3).設定中介軟體的順序很重要,中介軟體的巢狀順序是怎麼確定的 ?
思考以上標準中介軟體的行為: 輸入下一個中介軟體的執行委託Next, 定義當前中介軟體的執行委託Invoke/InvokeAsync;每個中介軟體完成了 Func<RequestDelegate,RequestDelegate>這樣的行為。
通過引數next與下一個中介軟體的執行委託Invoke/InvokeAsync 建立"鏈式"關係。
public delegate Task RequestDelegate(HttpContext context);
//---------------------------------------------節選自 Microsoft.AspNetCore.Builder.UseMiddlewareExtensions----------------------------------------------- /// <summary> /// Adds a middleware type to the application's request pipeline. /// </summary> /// <typeparam name="TMiddleware">The middleware type.</typeparam> /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param> /// <param name="args">The arguments to pass to the middleware type instance's constructor.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns> public static IApplicationBuilder UseMiddleware<TMiddleware>(this IApplicationBuilder app, params object[] args) { return app.UseMiddleware(typeof(TMiddleware), args); } /// <summary> /// Adds a middleware type to the application's request pipeline. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param> /// <param name="middleware">The middleware type.</param> /// <param name="args">The arguments to pass to the middleware type instance's constructor.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns> public static IApplicationBuilder UseMiddleware(this IApplicationBuilder app, Type middleware, params object[] args) { if (typeof(IMiddleware).GetTypeInfo().IsAssignableFrom(middleware.GetTypeInfo())) { // IMiddleware doesn't support passing args directly since it's // activated from the container if (args.Length > 0) { throw new NotSupportedException(Resources.FormatException_UseMiddlewareExplicitArgumentsNotSupported(typeof(IMiddleware))); } return UseMiddlewareInterface(app, middleware); } var applicationServices = app.ApplicationServices; return app.Use(next => { var methods = middleware.GetMethods(BindingFlags.Instance | BindingFlags.Public); var invokeMethods = methods.Where(m =>//執行委託被限制為Invoke/InvokeAsync string.Equals(m.Name, InvokeMethodName, StringComparison.Ordinal) || string.Equals(m.Name, InvokeAsyncMethodName, StringComparison.Ordinal) ).ToArray(); if (invokeMethods.Length > 1) { throw new InvalidOperationException(Resources.FormatException_UseMiddleMutlipleInvokes(InvokeMethodName, InvokeAsyncMethodName)); } if (invokeMethods.Length == 0) { throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoInvokeMethod(InvokeMethodName, InvokeAsyncMethodName, middleware)); } var methodInfo = invokeMethods[0]; if (!typeof(Task).IsAssignableFrom(methodInfo.ReturnType)) { throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNonTaskReturnType(InvokeMethodName, InvokeAsyncMethodName, nameof(Task))); } var parameters = methodInfo.GetParameters(); if (parameters.Length == 0 || parameters[0].ParameterType != typeof(HttpContext)) { throw new InvalidOperationException(Resources.FormatException_UseMiddlewareNoParameters(InvokeMethodName, InvokeAsyncMethodName, nameof(HttpContext))); } var ctorArgs = new object[args.Length + 1]; ctorArgs[0] = next; Array.Copy(args, 0, ctorArgs, 1, args.Length);//通過反射形成中介軟體例項的時候,建構函式第一個引數被指定為 下一個中介軟體的執行委託 var instance = ActivatorUtilities.CreateInstance(app.ApplicationServices, middleware, ctorArgs); if (parameters.Length == 1) { return (RequestDelegate)methodInfo.CreateDelegate(typeof(RequestDelegate), instance); } // 當前執行委託除了可指定HttpContext引數以外, 還可以注入更多的依賴引數 var factory = Compile<object>(methodInfo, parameters); return context => { var serviceProvider = context.RequestServices ?? applicationServices; if (serviceProvider == null) { throw new InvalidOperationException(Resources.FormatException_UseMiddlewareIServiceProviderNotAvailable(nameof(IServiceProvider))); } return factory(instance, context, serviceProvider); }; }); } //-----------------------------------節選自 Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder----------------------------------------------------- private readonly IList<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>(); publicIApplicationBuilder Use(Func<RequestDelegate,RequestDelegate>middleware) { this._components.Add(middleware); return this; } public RequestDelegate Build() { RequestDelegate app = context => { context.Response.StatusCode = 404; return Task.CompletedTask; }; foreach (var component in _components.Reverse()) { app = component(app); } return app; }
通過以上程式碼我們可以看出:
- 註冊中介軟體的過程實際上,是給一個 Type= List<Func<RequestDelegate, RequestDelegate>> 的容器依次新增元素的過程;
- 容器中每個元素對應每個中介軟體的行為委託Func<RequestDelegate, RequestDelegate>, 這個行為委託包含2個關鍵行為:輸入下一個中介軟體的執行委託next:RequestDelegate, 完成當前中介軟體的Invoke函式: RequestDelegate;
- 通過build方法完成前後中介軟體的鏈式傳值關係
分析原始碼:回答上面的問題:
- 使用 反射構造中介軟體 的時候,第一個引數Array[0] 是下一個中介軟體的執行委託
- 當前中介軟體執行委託 函式簽名 被限制 為: Invoke/InvokeAsync
- 按照程式碼順序新增進入 _components容器, 通過後一箇中間件的執行委託 -----(指向)----> 前一箇中間件的輸入執行委託建立鏈式關係。
附:非標準中介軟體的用法
短路中介軟體、 分叉中介軟體
整個處理管道的形成,存在一些管道分叉或者臨時插入中介軟體的行為,一些重要方法可供使用
- Use方法是一個註冊中介軟體的簡便寫法
- Run方法是一個約定,一些中介軟體使用Run方法來完成管道的結尾
- Map擴充套件方法:請求滿足指定路徑,將會執行分叉管道,強調滿足 path
- MapWhen方法:HttpContext滿足條件,將會執行分叉管道:
- UseWhen方法:選擇性的注入中介軟體