.Net Core中間件官網:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.0html
ASP.Net請求管道:ajax
請求最終會由一個具體的HttpHandler處理(page/ashx/mvc httphandler---action)。可是還有多個步驟,被封裝成事件,能夠註冊擴展,IHttpModule,提供了很是優秀的擴展。瀏覽器
可是這樣有一個缺陷,那就是太多管閒事了,一個http請求最核心的是IHttpHandler,其餘的Cookie、Session、Session、BeginRequest、EndRequest、MapRequestHandler、受權等,不必定非得有這些請求的事件的邏輯,可是寫死了,就必須得有,默認認爲那些步驟是必須有的,由於跟框架的設計思想有關。.Net Framework入門簡單精通難,由於框架大包大攬,全家桶式,WebForm裏面拖一個控件而後就能夠擼代碼了,一個項目就出來了,因此精通也難,也要付出代價,就是包袱比較重,不能輕裝前行。mvc
ASP.Net Core:app
ASP.NET Core 請求管道包含一系列請求委託,依次調用。 下圖演示了這一律念。 沿黑色箭頭執行。框架
ASP.NET Core是一套全新的平臺,已經再也不向前兼容,設計更追求組件化,追求高性能,沒有全家桶,那麼ASP.NET Core是怎麼搭建請求管道的呢?默認狀況,管道只有一個404。而後你也能夠增長請求的處理,這就是之前的Handler,只包含業務處理環節,其餘的就是中間件,MiddleWare。異步
一、Run 終結式 只是執行,沒有去調用Next ,通常做爲終結點。所謂Run終結式註冊,其實只是一個擴展方法,最終還不是得調用Use方法,async
app.Run(async (HttpContext context) => { await context.Response.WriteAsync("Hello World Run"); }); app.Run(async (HttpContext context) => { await context.Response.WriteAsync("Hello World Run Again"); });
二、Use表示註冊動做 不是終結點 ,執行next,就能夠執行下一個中間件 若是不執行,就等於Run組件化
app.Use(async (context, next) => { await context.Response.WriteAsync("Hello World Use1 <br/>"); await next(); await context.Response.WriteAsync("Hello World Use1 End <br/>"); }); app.Use(async (context, next) => { await context.Response.WriteAsync("Hello World Use2 Again <br/>"); await next(); });
UseWhen能夠對HttpContext檢測後,增長處理環節;原來的流程仍是正常執行的性能
app.UseWhen(context => { return context.Request.Query.ContainsKey("Name"); }, appBuilder => { appBuilder.Use(async (context, next) => { await context.Response.WriteAsync("Hello World Use3 Again Again Again <br/>"); await next(); }); });
app.Use(),沒有調用next(),那就是終結點,跟Run同樣
app.Use(async (context, next) => { await context.Response.WriteAsync("Hello World Use3 Again Again <br/>"); //await next(); });
三、Map:根據條件指定中間件 指向終結點,沒有Next,最好不要在中間件裏面判斷條件選擇分支;而是一箇中間件只作一件事兒,多件事兒就多箇中間件
app.Map("/Test", MapTest); app.Map("/Bingle", a => a.Run(async context => { await context.Response.WriteAsync($"This is Bingle Site"); })); app.MapWhen(context => { return context.Request.Query.ContainsKey("Name"); //拒絕非chorme瀏覽器的請求 //多語言 //把ajax統一處理 }, MapTest);
IApplicationBuilder 應用程序的組裝者,RequestDelegate:傳遞一個HttpContext,異步操做下,不返回;也就是一個處理動做,Use(Func<RequestDelegate, RequestDelegate> middleware) 委託,傳入一個RequestDelegate,返回一個RequestDelegate。ApplicationBuilder裏面有個容器IList<Func<RequestDelegate, RequestDelegate>> _components,Use就只是去容器裏面添加個元素。最終會Build()一下, 若是沒有任何註冊,就直接404處理一切,
foreach (var component in _components.Reverse())//反轉集合 每一個委託拿出來 { app = component.Invoke(app); //委託3-- 404做爲參數調用,返回 委託3的內置動做--做爲參數去調用委託(成爲了委託2的參數)--循環下去---最終獲得委託1的內置動做---請求來了HttpContext--- }
IApplicationBuilder build以後其實就是一個RequestDelegate,能對HttpContext加以處理,默認狀況下,管道是空的,就是404;能夠根據你的訴求,任意的配置執行,一切所有由開發者自由定製,框架只是提供了一個組裝方式
其實,中間件能夠這樣寫。
Func<RequestDelegate, RequestDelegate> middleware = next => { return new RequestDelegate(async context => { await context.Response.WriteAsync("<h3>This is Middleware1 start</h3>"); await Task.CompletedTask; await next.Invoke(context);//RequestDelegate--須要context返回Task await context.Response.WriteAsync("<h3>This is Middleware1 end</h3>"); }); }; app.Use(middleware);
每次都要這麼麻煩,去定義一個Func<RequestDelegate,RequestDelegate>,而後去使用嗎?咱們能夠進化一點點
app.Use(next => { System.Diagnostics.Debug.WriteLine("this is Middleware1"); return new RequestDelegate(async context => { await context.Response.WriteAsync("<h3>This is Middleware1 start</h3>"); await next.Invoke(context); await context.Response.WriteAsync("<h3>This is Middleware1 end</h3>"); }); }); app.Use(next => { System.Diagnostics.Debug.WriteLine("this is Middleware2"); return new RequestDelegate(async context => { await context.Response.WriteAsync("<h3>This is Middleware2 start</h3>"); await next.Invoke(context); await context.Response.WriteAsync("<h3>This is Middleware2 end</h3>"); }); }); app.Use(next => { System.Diagnostics.Debug.WriteLine("this is Middleware3"); return new RequestDelegate(async context => { await context.Response.WriteAsync("<h3>This is Middleware3 start</h3>"); //await next.Invoke(context);//註釋掉,表示再也不往下走 await context.Response.WriteAsync("<h3>This is Middleware3 end</h3>"); }); });
執行的結果,順序爲:
<h3>This is Middleware1 start</h3> <h3>This is Middleware2 start</h3> <h3>This is Middleware3 start</h3> <h3>This is Middleware3 end</h3> <h3>This is Middleware2 end</h3> <h3>This is Middleware1 end</h3>
和之前ActionFilter是否是很像,是一個俄羅斯套娃,我比較喜歡說成洋蔥模型。實際上是由於源碼中,將IList<Func<RequestDelegate,RequestDelegate>> _components,將_components.Reverse()使集合反轉了。
那中間件的代碼,下面這種寫法很差嗎?
app.Use(async (context, next) => { //Do work that doesn't write to the Response await next.Invoke(); //Do logging or other work that doesn't write to the Response }); app.Run(async context => { await context.Response.WriteAsync("Hello from 2nd delegate."); });
ApplicationBuilder裏面有個容器IList<Func<RequestDelegate,RequestDelegate>> _components。Use的時候就只是去容器裏面添加個元素,最終Build()一下,若是沒有任何註冊,就直接404處理一切。
委託3---404做爲參數調用,返回委託3的內置動做---做爲參數去調用委託(成爲了委託2的參數)---循環下去,最終獲得委託1的內置動做,請求來了HttpContext,IApplicationBuilder,build以後其實就是一個RequestDelegate,能對HttpContext加以處理,默認狀況下,管道是空的,就是404,能夠根據你的訴求,任意的配置執行,一切全有開發者自由定製,框架只是提供了一個組裝方式。
中間件裏面的邏輯能夠封裝到一個類中去:
public class FirstMiddleWare { private readonly RequestDelegate _next; public FirstMiddleWare(RequestDelegate next) { this._next = next; } public async Task Invoke(HttpContext context) { await context.Response.WriteAsync($"{nameof(FirstMiddleWare)},Hello World1!<br/>"); await _next(context); await context.Response.WriteAsync($"{nameof(FirstMiddleWare)},Hello World2!<br/>"); } }
在使用的時候:
app.UseMiddleware<FirstMiddleWare>();
其實,咱們能夠再升級一點點,使用擴展方法,將這個類中的邏輯做爲IApplicationBuilder的擴展方法。
public static class MiddleExtend { public static IApplicationBuilder UseFirstMiddleWare(this IApplicationBuilder builder) { return builder.UseMiddleware<FirstMiddleWare>(); } }
在使用的時候就簡單多了
app.UseFirstMiddleWare();