ASP.NET Core 中间件(Middleware)的使用及其源码解析(三)- 对中间件管道进行分支
如果业务逻辑比较简单的话,一条主管道就够了,确实用不到分支管道。不过当业务逻辑比较复杂的时候,有时候我们可能希望根据情况的不同使用特殊的一组中间件来处理 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; } } }
其中 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 { /// <summary> /// Represents a middleware that runs a sub-request pipeline when a given predicate is matched. /// </summary> public class MapWhenMiddleware { private readonly RequestDelegate _next; private readonly MapWhenOptions _options; /// <summary> /// Creates a new instance of <see cref="MapWhenMiddleware"/>. /// </summary> /// <param name="next">The delegate representing the next middleware in the request pipeline.</param> /// <param name="options">The middleware options.</param> public MapWhenMiddleware(RequestDelegate next, MapWhenOptions 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)); } if (_options.Predicate(context)) { await _options.Branch(context); } else { await _next(context); } } } }
Map 主要通过 URL 中的 Path 来判断是否需要进入分支管道,但有时候我们很可能会有别的需求,例如我想对所有 Method 为 DELETE 的请求用特殊管道处理,这时候就需要用 MapWhen 了。MapWhen 是一种通用的 Map,可以由使用者来决定什么时候进入分支管道什么时候不进入。可以说 Map 是 MapWhen 的一种情况,因为这种情况太常见了,所以官方实现了一个。这样看来 MapWhen 就很简单了,在 Map 中我们传入参数 PathString 来进行 HttpRequest.Path 的匹配,而在 MapWhen 中我们传入 Func<HttpContext, bool> 参数,由我们自行指定,当返回 true 时进入分支管道,返回 false 则继续当前管道。
3、UseWhen扩展原理
我们将光标移动到 UseWhen 处按 F12 转到定义,如下所示:
可以发现它是位于 UseWhenExtensions 扩展类中的,我们找到 UseWhenExtensions 类的源码,如下所示:
// 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; namespace Microsoft.AspNetCore.Builder { using Predicate = Func<HttpContext, bool>; /// <summary> /// Extension methods for <see cref="IApplicationBuilder"/>. /// </summary> public static class UseWhenExtensions { /// <summary> /// Conditionally creates a branch in the request pipeline that is rejoined to the main pipeline. /// </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 UseWhen(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 and configure the branch builder right away; otherwise, // we would end up running our branch after all the components // that were subsequently added to the main builder. var branchBuilder = app.New(); configuration(branchBuilder); return app.Use(main => { // This is called only when the main application builder // is built, not per request. branchBuilder.Run(main); var branch = branchBuilder.Build(); return context => { if (predicate(context)) { return branch(context); } else { return main(context); } }; }); } } }
UseWhen 也基于给定谓词的结果创建请求管道分支。 与 MapWhen 不同的是,如果这个分支不发生短路或包含终端中间件,则会重新加入主管道。
仔细阅读上面的源码后我们会发现,其实 Map/MapWhen/UseWhen 均为 app.Use(...) 的封装,主要是为了熟悉的人方便而已。
本文部分内容参考博文:https://www.cnblogs.com/durow/p/5752055.html
更多关于ASP.NET Core 中间件的相关知识可参考微软官方文档: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0
至此本文就全部介绍完了,如果觉得对您有所启发请记得点个赞哦!!!
Demo源码:
链接:https://pan.baidu.com/s/18I66dBmKZUpfPCNn85HI2g 提取码:2xcj
此文由博主精心撰写转载请保留此原文链接:https://www.cnblogs.com/xyh9039/p/16492284.html
版权声明:如有雷同纯属巧合,如有侵权请及时联系本人修改,谢谢!!!