[Middleware] Using Middleware in Asp.Net Core
[Middleware] Using Middleware in Asp.Net Core
因為在 Asp.Net Core 中,它本身是一個管線的概念,Middleware 本身就是坐落在管線之中,所以我們可以透過 Middleware , 一直在管線中,安插我們想要執行的一些程式邏輯。
Middleware
Middleware 基本上需要注入 RequestDelegate,也需要實作 Invoke 方法。有一點需要注意的是,在 Invoke 中,一定要呼叫 RequestDelegate 方法, 否則管線運行時,運行到此 middleware 就會停止於目前的管線中。
public class MyMiddleware
{
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public RequestDelegate _next { get; }
public async Task Invoke(HttpContext context)
{
Console.WriteLine("Hello, I am in Middleware!");
await _next(context);
}
}
Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// 將 Middleware 排入 管線中
app.UseMiddleware<MyMiddleware>();
app.UseMvc();
}
Result
MiddlewareExample> Content root path: C:\Project\RFF\MiddlewareExample
MiddlewareExample> Now listening on: http://localhost:11496
MiddlewareExample> Application started. Press Ctrl+C to shut down.
MiddlewareExample> Hello, I am in Middleware!
留言
張貼留言