中间件是一种插入到管道上进行处理请求和响应的软件;每一个中间件组件具备下面的功能:session
请求委托(request delegate)是用于创建(build)请求管道的,请求委托能够处理每一个Http的请求;app
请求委托被配置的方法有三种:Run、Map、Use 扩展方法;async
请求管道由一系列请求委托组成,一个调用一个;以下图函数
每一个委托均可以在下一个委托以前和以后执行。异常处理的委托在管道中被尽早调用,由于它能够捕获到后面管道中发生的错误。ui
使用一个匿名函数处理每一个 Http 请求;而且使用的是 run ,它表示管道的结束,即最后一个中间件,不会再传递到下一个中间件spa
public class Startup { public void Configure(IApplicationBuilder app) { app.Run(async context => { await context.Response.WriteAsync("Hello, World!"); }); } }
next 参数 表明管道中的下一个委托,能够在下一个委托以前和以后进行处理;你也能够不调用 next 参数,直接短路管道(即不会传递到下一个委托/中间件)。code
public class Startup { public void Configure(IApplicationBuilder app) { app.Use(async (context, next) => { // Do work that doesn't write to the Response. await next.Invoke(); // Do logging or other work that doesn't write to the Response. }); app.Run(async context => { await context.Response.WriteAsync("Hello from 2nd delegate."); }); } }
这里的顺序是指中间件被加到 Startup.Configure 方法的顺序决定了中间件顺序处理请求和逆序处理响应。因此,添加顺序是很重要的orm
通常的应用中的 Startup.Configure 方法添加中间组件的顺序:server
public void Configure(IApplicationBuilder app) { if (env.IsDevelopment()) { // When the app runs in the Development environment: // Use the Developer Exception Page to report app runtime errors. // Use the Database Error Page to report database runtime errors.
// 添加异常中间件以后,后面中间件发生的异常都会被捕获
app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { // When the app doesn't run in the Development environment: // Enable the Exception Handler Middleware to catch exceptions // thrown in the following middlewares. // Use the HTTP Strict Transport Security Protocol (HSTS) // Middleware. app.UseExceptionHandler("/Error"); app.UseHsts(); } // Use HTTPS Redirection Middleware to redirect HTTP requests to HTTPS.使用https重定向中间件来重定向http请求到https请求 app.UseHttpsRedirection(); // Return static files and end the pipeline. app.UseStaticFiles(); // Use Cookie Policy Middleware to conform to EU General Data // Protection Regulation (GDPR) regulations. app.UseCookiePolicy(); // Authenticate before the user accesses secure resources. app.UseAuthentication(); // If the app uses session state, call Session Middleware after Cookie // Policy Middleware and before MVC Middleware. app.UseSession(); // Add MVC to the request pipeline. app.UseMvc(); }
使用 Use , Run 和 Map 配置 HTTP 管道。中间件
Use 方法若是不调用next 就会形成短路;
一些中间件组件可能会暴露 Run [ Middleware ] 方法 在管道的结束处运行;
Map 扩展 主要用做一种分支管道的惯例:
Map* 根据这给出的请求路径是否匹配来进入管道。
public 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>"); }); } }
若是路径匹配 /map1 ,则执行 HandleMapTest1;
若是路径匹配 /map2 , 则执行 HandleMapTest2 ;
以下示例:
MapWhen 的用法
当知足某个条件时,执行
public class Startup { private static void HandleBranch(IApplicationBuilder app) { app.Run(async context => { var branchVer = context.Request.Query["branch"]; await context.Response.WriteAsync($"Branch used = {branchVer}"); }); } public void Configure(IApplicationBuilder app) { app.MapWhen(context => context.Request.Query.ContainsKey("branch"), HandleBranch); app.Run(async context => { await context.Response.WriteAsync("Hello from non-Map delegate. <p>"); }); } }
示例以下:
另外,map支持嵌套
app.Map("/level1", level1App => { level1App.Map("/level2a", level2AApp => { // "/level1/level2a" processing }); level1App.Map("/level2b", level2BApp => { // "/level1/level2b" processing }); });
并且,map支持每次匹配多个段
public class Startup { private static void HandleMultiSeg(IApplicationBuilder app) { app.Run(async context => { await context.Response.WriteAsync("Map multiple segments."); }); } public void Configure(IApplicationBuilder app) { app.Map("/map1/seg1", HandleMultiSeg); //此句示例 app.Run(async context => { await context.Response.WriteAsync("Hello from non-Map delegate."); }); } }
另外还有不少内置的中间件可供使用,可根据须要进行使用
参考网址:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.2