回到目錄html
在進行.net core平臺以後,咱們若是但願在請求過程當中添加一些事件是很是容易的,你能夠把這些事件作成一箇中間件Middleware,而後這些中間件就會以Http pipeline的管道方式進行相應,而且它們就像是一個職責鏈,從你定義的第一個中間件開始,一個一個向下傳遞,直到最後一箇中間件完成爲止!api
前幾天我寫了在.net core裏實現模塊化服務,DotNetCore跨平臺~組件化時代來了 主要是將咱們定義的組件添加到IServiceCollection集合裏,而後在程序啓動後去註冊它們,而今天要說的Middleware用到的是IApplicationBuilder,它在程序啓動後,加載與http請求相關的組件,這些組件以Pipeline的形式進行處理,也就是咱們所說的中間件,下面我來帶你們實現一個最簡單的Middleware!mvc
從網上找的圖,挺形象app
圖中記錄了一個請求進來,通過各個中間件的處理,最後逐個響應,下面咱們來看一下簡單的代碼實現,和服務組件化同樣,也是一個實現,一個擴展方法的調用,最後在startup裏去使用它。框架
大叔Lind.DotNetCore框架裏的Middlewareasync
ResponseTimeMiddleware的實現模塊化
/// <summary> /// 響應時間的中間件 /// </summary> public class ResponseTimeMiddleware { private readonly RequestDelegate _next; public ResponseTimeMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { Stopwatch sw = new Stopwatch(); sw.Start(); Console.WriteLine("ResponseTimeMiddleware..."); await _next.Invoke(context); sw.Stop(); Console.WriteLine($"頁面響應時間爲:{sw.ElapsedMilliseconds}ms"); } }
擴展方法去封裝它,以便於其它地方去使用它組件化
/// <summary> /// Lind.DotNetCore.Middleware擴展方法 /// </summary> public static class MiddlewareExtensions { public static IApplicationBuilder UseResponseTime(this IApplicationBuilder builder) { return builder.UseMiddleware<ResponseTimeMiddleware>(); } public static IApplicationBuilder UseRequestKey(this IApplicationBuilder builder) { return builder.UseMiddleware<RequestKeyMiddleware>(); } public static IApplicationBuilder UseAuthorizationOperation(this IApplicationBuilder builder) { return builder.UseMiddleware<AuthorizationOperationMiddleware>(); } }
最後在startup裏使用它,注意是在AddMvc方法前面,要否則對你的mvc,api是無效的,呵呵!post
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseAuthorizationOperation(); app.UseResponseTime(); app.UseRequestKey(); app.UseStaticHttpContext(); app.UseMvc();
事實上,今天的中間件是.net core裏很是大的亮點,其實早就應該寫這篇文章了,呵呵!ui
感謝各位的閱讀!