.Net Core中間件官網:https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/middleware/?view=aspnetcore-3.0
ASP.Net請求管道:

請求最侄訓由一個具體的HttpHandler處理(page/ashx/mvc httphandler---action),但是還有多個步驟,被封裝成事件,可以注冊擴展,IHttpModule,提供了非常優秀的擴展,
但是這樣有一個缺陷,那就是太多管閑事了,一個http請求最核心的是IHttpHandler,其他的Cookie、Session、Session、BeginRequest、EndRequest、MapRequestHandler、授權等,不一定非得有這些請求的事件的邏輯,但是寫死了,就必須得有,默認認為那些步驟是必須有的,因為跟框架的設計思想有關,.Net Framework入門簡單精通難,因為框架大包大攬,全家桶式,WebForm里面拖一個控制元件然后就可以擼代碼了,一個專案就出來了,所以精通也難,也要付出代價,就是包袱比較重,不能輕裝前行,
ASP.Net Core:
ASP.NET Core 請求管道包含一系列請求委托,依次呼叫, 下圖演示了這一概念, 沿黑色箭頭執行,

ASP.NET Core是一套全新的平臺,已經不再向前兼容,設計更追求組件化,追求高性能,沒有全家桶,那么ASP.NET Core是怎么搭建請求管道的呢?默認情況,管道只有一個404,然后你也可以增加請求的處理,這就是以前的Handler,只包含業務處理環節,其他的就是中間件,MiddleWare,
1、Run 終結式 只是執行,沒有去呼叫Next ,一般作為終結點,所謂Run終結式注冊,其實只是一個擴展方法,最侄訓不是得呼叫Use方法,
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"); });
2、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(); });
3、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();
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/114315.html
標籤:.NET Core
上一篇:asp.net core3.0 mvc 用 autofac
下一篇:asp.net core IdentityServer4 實作 resource owner password credentials(密碼憑證)
