.NetCore中的Middleware是裝配到管道處理請求和響應的組件;每一個組件均可以決定是否繼續進入下一個管道、而且能夠在進入下一個管道先後執行邏輯;安全
最後一個管道或者中斷管道的中間件叫終端中間件;服務器
一、建立中間件管道IApplicationBuilderapp
app.Run()攔截請求後中斷請求,多個Run()只執行第一個;async
app.Run(async httpcontenxt => { httpcontenxt.Response.ContentType = "text/plain; charset=utf-8"; await httpcontenxt.Response.WriteAsync("截獲請求!並在此後中斷管道"); }); app.Run(async httpcontenxt => { httpcontenxt.Response.ContentType = "text/plain; charset=utf-8"; await httpcontenxt.Response.WriteAsync("排序第二個的RUN"); });
二、鏈接下一個管道 Use()ui
使用next.invoke調用下一個管道,在向客戶端發送響應後,不容許調用 next.Invoke,會引起異常spa
app.Use(async (context, next) => { // 執行邏輯,但不能寫Response //調用管道中的下一個委託 await next.Invoke(); // 執行邏輯,如日誌等,但不能寫Response }); app.Run(async httpcontenxt => { httpcontenxt.Response.ContentType = "text/plain; charset=utf-8"; await httpcontenxt.Response.WriteAsync("截獲請求!並在此後中斷管道"); }); app.Run(async httpcontenxt => { httpcontenxt.Response.ContentType = "text/plain; charset=utf-8"; await httpcontenxt.Response.WriteAsync("排序第二個的RUN"); });
三、經過路徑或條件處理管道 Map()日誌
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}"); }); } private static void HandleMapTest2(IApplicationBuilder app) { app.Run(async context => { await context.Response.WriteAsync("Map Test 2"); }); } public void Configure(IApplicationBuilder app) { app.MapWhen(context => context.Request.Query.ContainsKey("branch"), HandleBranch);//localhost:1234/?branch=master app.Map("/map2", HandleMapTest2);//localhost:1234/map2 app.Run(async context => { await context.Response.WriteAsync("Hello from non-Map delegate. <p>"); }); } }
四、中間件的順序很重要code
異常/錯誤處理
HTTP 嚴格傳輸安全協議
HTTPS 重定向
靜態文件服務器
Cookie 策略實施
身份驗證
會話
MVC中間件
app.UseExceptionHandler("/Home/Error"); // Call first to catch exceptions app.UseStaticFiles(); // Return static files and end pipeline. app.UseAuthentication(); // Authenticate before you access app.UseMvcWithDefaultRoute();
資源blog
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/index?view=aspnetcore-2.2