概念
- 在pipeline中判斷是否將請求傳遞給下一個組件
- 在處理管道的下個組件執行之前和之後執行一些工作, HttpContxt對象能跨域請求、響應的執行週期
特性和行爲
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();
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);
// 執行委託名稱被限制爲Invoke/InvokeAsync var invokeMethods = methods.Where(m => 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, 函數支持傳入除HttpContext之外的參數
- 按照代碼順序添加進入 _components容器, 通過後一箇中間件的執行委託 -----(指向)----> 前一箇中間件的輸入執行委託建立鏈式關係。
附:非標準中間件的用法
短路中間件、 分叉中間件
- Use方法是一個註冊中間件的簡便寫法
- Run方法是一個約定,一些中間件使用Run方法來完成管道的結尾
- Map擴展方法:請求滿足指定路徑,將會執行分叉管道,強調滿足 path
- MapWhen方法:HttpContext滿足條件,將會執行分叉管道:
- UseWhen方法:選擇性的注入中間件