1. 程式人生 > >Net Core:Middleware中間件管道

Net Core:Middleware中間件管道

iap lin contains ons 日誌 tco idt ces configure

.NetCore中的Middleware是裝配到管道處理請求和響應的組件;每個組件都可以決定是否繼續進入下一個管道、並且可以在進入下一個管道前後執行邏輯;

最後一個管道或者中斷管道的中間件叫終端中間件;

技術分享圖片

1、創建中間件管道IApplicationBuilder

app.Run()攔截請求後中斷請求,多個Run()只執行第一個;

            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
"); });

2、連接下一個管道 Use()

使用next.invoke調用下一個管道,在向客戶端發送響應後,不允許調用 next.Invoke,會引發異常

            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"); });

3、通過路徑或條件處理管道 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>");
        });
    }
}

4、中間件的順序很重要

異常/錯誤處理
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();  

資源

https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/index?view=aspnetcore-2.2

Net Core:Middleware中間件管道