长宁区企业网站建设,wordpress 虾米音乐插件,中装建设算力租赁,免费国外医疗静态网站模板下载.net core 管道#xff08;Pipeline#xff09;是什么#xff1f;由上图可以看出#xff0c;.net core 管道是请求抵达服务器到响应结果返回的中间的一系列的处理过程#xff0c;如果我们简化一下成下图来看的话#xff0c;.net core 的管道其实就是中间件的部分。微软中… .net core 管道Pipeline是什么由上图可以看出.net core 管道是请求抵达服务器到响应结果返回的中间的一系列的处理过程如果我们简化一下成下图来看的话.net core 的管道其实就是中间件的部分。微软中间件文档为什么管道就是中间件的部分了呢我是这么理解的.net core 是通过Startup 类配置服务和应用的请求管道所以狭义点来讲这个管道就是指的请求管道就是我们今天要理解的中间件管道。.net core 核心体系结构的特点就是一个中间件系统它是处理请求和响应的代码段。中间件彼此链接形成一个管道。传入的请求通过管道传递其中每个中间件都有机会在将它们传递到下一个中间件之前对它们进行处理。传出响应也以相反的顺序通过管道传递。PS简单来讲就是请求开始到响应结束的中间的一大部分。你可以理解成 汽车销售 开始买车到提车的过程但愿不会坐在奔驰车盖上哭哈哈……还有我们来看看为什么我们要简化来看在运行时 .net core 会预先注入一些必要的服务及依赖项默认注入ServiceCollection的服务清单如下我们先断章取义地看这里面有 Kestrel 处理请求将接收到的请求内容字符串流转化成结构化的数据HttpContext供后面的中间件使用的服务。欸服务哟。那其实也就是 Kestrel 服务也是中间件嘛。而第一张图中的MVC本身也作为中间件来实现的。还有一些相关的服务都可以看看上面截图的服务而且旁边标注的生命周期的类型就是之前所讲到的 .net core 的三种注入模式 。那么从程序入口来讲过程是怎么样的呢从应用程序主入口 Main() -- WebHost -- UseStartup /// summary/// Specify the startup type to be used by the web host./// /summary/// param namehostBuilderThe see crefT:Microsoft.AspNetCore.Hosting.IWebHostBuilder / to configure./param/// param namestartupTypeThe see crefT:System.Type / to be used./param/// returnsThe see crefT:Microsoft.AspNetCore.Hosting.IWebHostBuilder /./returnspublic static IWebHostBuilder UseStartup(this IWebHostBuilder hostBuilder, Type startupType){string name startupType.GetTypeInfo().Assembly.GetName().Name;return hostBuilder.UseSetting(WebHostDefaults.ApplicationKey, name).ConfigureServices((ActionIServiceCollection)delegate(IServiceCollection services) {if (typeof(IStartup).GetTypeInfo().IsAssignableFrom(startupType.GetTypeInfo())) { ServiceCollectionServiceExtensions.AddSingleton(services, typeof(IStartup), startupType); }else { ServiceCollectionServiceExtensions.AddSingleton(services, typeof(IStartup), (FuncIServiceProvider, object)delegate(IServiceProvider sp) { IHostingEnvironment requiredService ServiceProviderServiceExtensions.GetRequiredServiceIHostingEnvironment(sp);return new ConventionBasedStartup(StartupLoader.LoadMethods(sp, startupType, requiredService.get_EnvironmentName())); }); } });}上面的代码就可以解释说会预先注入的必要的服务在通过委托的方式注入 Startup 里的服务。具体可以继续探究UseSettingAdd or replace a setting in the configuration./// summary/// Add or replace a setting in the configuration./// /summary/// param namekeyThe key of the setting to add or replace./param/// param namevalueThe value of the setting to add or replace./param/// returnsThe see crefT:Microsoft.AspNetCore.Hosting.IWebHostBuilder /./returnspublic IWebHostBuilder UseSetting(string key, string value){ _config.set_Item(key, value);return this;}ConfigureServicesAdds a delegate for configuring additional services for the host or web application. This may be called multiple times./// summary/// Adds a delegate for configuring additional services for the host or web application. This may be called/// multiple times./// /summary/// param nameconfigureServicesA delegate for configuring the see crefT:Microsoft.Extensions.DependencyInjection.IServiceCollection /./param/// returnsThe see crefT:Microsoft.AspNetCore.Hosting.IWebHostBuilder /./returnspublic IWebHostBuilder ConfigureServices(ActionIServiceCollection configureServices){if (configureServices null) {throw new ArgumentNullException(configureServices); }return ConfigureServices(delegate(WebHostBuilderContext _, IServiceCollection services) { configureServices(services); });} ConventionBasedStartuppublic class ConventionBasedStartup : IStartup{private readonly StartupMethods _methods;public ConventionBasedStartup(StartupMethods methods) { _methods methods; }public void Configure(IApplicationBuilder app) {try { _methods.ConfigureDelegate(app); }catch (Exception ex) {if (ex is TargetInvocationException) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); }throw; } }public IServiceProvider ConfigureServices(IServiceCollection services) {try {return _methods.ConfigureServicesDelegate(services); }catch (Exception ex) {if (ex is TargetInvocationException) { ExceptionDispatchInfo.Capture(ex.InnerException).Throw(); }throw; } }} OK到这里就已经确定了我们可控的是通过Startup注入我们所需的服务就是Startup注入的中间件可以做所有的事情如处理认证错误静态文件等等并且如上面所说的 MVC 在 .net core 也是作为中间件实现的。那么 .net core 给我们内置了多少中间件呢如下图我们很经常用到的内置中间件有 app.UseExceptionHandler(); //异常处理 app.UseStaticFiles(); //静态文件 app.UseAuthentication(); //Auth验证 app.UseMvc(); //MVC我们知道可以在启动类的 Configure 方法中配置 .net core 管道通过调用 IApplicationBuilder 上的 Use*** 方法就可以向管道添加一个中间件被添加的顺序决定了请求遍历它们的顺序。因此如上面添加内置中间件的顺序传入的请求将首先遍历异常处理程序中间件然后是静态文件中间件然后是身份验证中间件最终将由MVC中间件处理。Use*** 方法实际上只是 .net core 提供给我们的“快捷方式”以便更容易地构建管道。在幕后它们最终都使用直接或间接这些关键字Use 和 Run 。两者都向管道中添加了一个中间件不同之处在于Run添加了一个终端中间件即管道中的最后一个中间件。那么有内置就应该可以定制的。如何定制自己的中间件呢上一些简陋的demo演示一下1无分支管道// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.public void Configure(IApplicationBuilder app, IHostingEnvironment env){// Middleware A app.Use(async (context, next) { Console.WriteLine(A (before));await next(); Console.WriteLine(A (after)); });// Middleware B app.Use(async (context, next) { Console.WriteLine(B (before));await next(); Console.WriteLine(B (after)); });// Middleware C (terminal) app.Run(async context { Console.WriteLine(C);await context.Response.WriteAsync(Hello world); });}打印结果A (before)B (before)CB (after)A (after)那用管道图展示的话就是2有分支管道当使用无分支的管道时相当于就是一条线直走到底再返回响应结果。但一般情况下我们都希望管道更具灵活性。创建有分支的管道就需要使用到 Map 扩展用作约定来创建管道分支。Map 是基于给定请求路径的匹配项来创建请求管道分支的如果请求路径以给定的路径开头就执行分支。那么就有两种类型有分支的管道1.无连结分支上官方demopublic class Startup{private static void HandleMapTest1(IApplicationBuilder app) { app.Run(async context {await context.Response.WriteAsync(Map Test 1); }); }private static void HandleMapTest2(IApplicationBuilder app) { app.Run(async context {await context.Response.WriteAsync(Map Test 2); }); }public void Configure(IApplicationBuilder app) { app.Map(/map1, HandleMapTest1); app.Map(/map2, HandleMapTest2); app.Run(async context {await context.Response.WriteAsync(Hello from non-Map delegate. p); }); }}结果以上无连结分支很容易就理解了就是不同的路径跑不同的分支。如果是有参数匹配的话就要使用 MapWhen而 MapWhen 基于给定谓词的结果创建请求管道分支。FuncHttpContext, bool 类型的任何谓词均可用于将请求映射到管道的新分支。谓词用于检测查询字符串变量 branch 是否存在。2.有连结重新连接上主管道分支创建有连结分支管道就要使用到 UseWhen上demopublic void Configure(IApplicationBuilder app){ app.Use(async (context, next) { Console.WriteLine(A (before));await next(); Console.WriteLine(A (after)); }); app.UseWhen( context context.Request.Path.StartsWithSegments(new PathString(/foo)), a a.Use(async (context, next) { Console.WriteLine(B (before));await next(); Console.WriteLine(B (after)); })); app.Run(async context { Console.WriteLine(C);await context.Response.WriteAsync(Hello world); });}像上面的代码当请求不是以 /foo 开头的时候结果为当请求是以 /foo 开头的时候结果为A (before)B (before)CB (after)A (after) 正如您所看到的中间件管道背后的思想非常简单但是非常强大。大多数功能都是 .net core(身份验证、静态文件、缓存、MVC等)作为中间件实现。当然编写自己的代码也很容易 后面可以进阶写自己的中间件官方文档。原文地址https://www.cnblogs.com/Vam8023/p/10700254.html.NET社区新闻深度好文欢迎访问公众号文章汇总 http://www.csharpkit.com