NetCore訊息管道 Middleware

DaiWK發表於2024-07-16

中介軟體定義

/// <summary>
/// 自定義中介軟體1
/// </summary>
public class MyMiddleware : IMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        Console.WriteLine("MyMiddleware_1,開始處理");
        await next.Invoke(context);
        Console.WriteLine("MyMiddleware_1,結束");
    }
}

/// <summary>
/// 自定義中介軟體2
/// </summary>
public class MyMiddleware2 : IMiddleware
{
    public async Task InvokeAsync(HttpContext context, RequestDelegate next)
    {
        Console.WriteLine("MyMiddleware_2,開始處理");
        await next.Invoke(context);
        Console.WriteLine("MyMiddleware_2,結束");
    }
}

/// <summary>
/// 透過擴充方法呼叫
/// </summary>
public static class Middleware2AppBuilderExtensions
{
    public static IApplicationBuilder UseMiddleware2(this IApplicationBuilder app)
    {
        return app.UseMiddleware<MyMiddleware2>();
    }
}

中介軟體註冊

//注入中介軟體
builder.Services.AddSingleton<MyMiddleware>();
builder.Services.AddSingleton<MyMiddleware2>();

訊息管道中加入中介軟體處理

//UseMiddleware方式呼叫
app.UseMiddleware<MyMiddleware>();
//擴充方式呼叫
app.UseMiddleware2();

//Use方式加入處理邏輯到訊息管道
app.Use(async (context, next) =>
{
    // await context.Response.WriteAsync("Begin Custom Middleward");
    Console.WriteLine("Begin Custom Middleward");
   await next.Invoke();
    // await context.Response.WriteAsync("End Custom Middleward");
    Console.WriteLine("End Custom Middleward");
});

//Run方式作為處理終結點,不再呼叫下一個middleward
app.Run(async (context) =>
{
    //await context.Response.WriteAsync("Middleward EndPoint");
    Console.WriteLine("Middleward EndPoint");
});

執行結果

相關文章