本篇將介紹 ASP.NET Core 的 Middleware,透過 Middleware 掌握封包的進出。
Middleware 運作方式
ASP.NET Core 的每個 Request 都會經過所有註冊的 Middleware,Response 也是逐一回傳,以先進後出的方式處裡封包。
Request 流程如下圖:
1. 建立 Middleware
Middleware 取代了 ASP.NET MVC 的 HTTP Modules 及 HTTP Handlers,使用方式更為簡潔。
此範例我建立了三個 Middleware,分別在 Request 及 Response 的部分輸出訊息。
如下:
FirstMiddleware.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class FirstMiddleware { private readonly RequestDelegate _next;
public FirstMiddleware(RequestDelegate next) { _next = next; }
public async Task Invoke(HttpContext context) { await context.Response.WriteAsync($"{nameof(FirstMiddleware)} in. \r\n");
await _next(context);
await context.Response.WriteAsync($"{nameof(FirstMiddleware)} out. \r\n"); } }
|
SecondMiddleware.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class SecondMiddleware { private readonly RequestDelegate _next;
public SecondMiddleware(RequestDelegate next) { _next = next; }
public async Task Invoke(HttpContext context) { await context.Response.WriteAsync($"{nameof(SecondMiddleware)} in. \r\n");
await _next(context);
await context.Response.WriteAsync($"{nameof(SecondMiddleware)} out. \r\n"); } }
|
ThirdMiddleware.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| public class ThirdMiddleware { private readonly RequestDelegate _next;
public ThirdMiddleware(RequestDelegate next) { _next = next; }
public async Task Invoke(HttpContext context) { await context.Response.WriteAsync($"{nameof(ThirdMiddleware)} in. \r\n");
await _next(context);
await context.Response.WriteAsync($"{nameof(ThirdMiddleware)} out. \r\n"); } }
|
2. 註冊 Middleware
在 Startup.cs 註冊 Middleware:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public class Startup { public void Configure(IApplicationBuilder app) { app.UseMiddleware<FirstMiddleware>(); app.UseMiddleware<SecondMiddleware>(); app.UseMiddleware<ThirdMiddleware>();
app.Run(async (context) => { await context.Response.WriteAsync("Hello World! \r\n"); }); } }
|
執行結果
程式碼下載
asp-net-core-middleware
參考
ASP.NET Core Middleware Fundamentals