探究ASP.NET Core Middleware 实现
概念
- 在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); 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); } 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方法:选择性的注入中间件