ASP.NET Core-注冊中間件(Use、UseMiddleWare、Map、Run)


使用IApplicationBuilder注冊中間件

 

Use():

app.Use(async (context, next) => { await context.Response.WriteAsync("hello world"); await next.Invoke(); }); 

app.Use((requestDelegate)
=> { return async (context) => { await context.Response.WriteAsync("hello world2"); await requestDelegate(context); }; });

 

 

UseMiddleWare():將中間件封裝,最終是使用Use注冊

        //自定義中間件
        public class TestMiddelware { public RequestDelegate _next; public TestMiddelware(RequestDelegate next) { this._next = next; } public Task Invoke(HttpContext context) { if (context.Request.Path.Value.Contains("1.jpg")) { return context.Response.SendFileAsync("1.jpg"); } if (this._next != null) { return this._next(context); } throw new Exception("TestMiddelware error"); } } app.UseMiddleware<TestMiddelware>(app, Array.Empty<object>());

 

Run(RequestDelegate handler):

終結點,在管道尾端增加一個中間件,之后的中間件不再執行 

app.Run(async context => { await context.Response.WriteAsync("hello world3"); });

 

Map()、MapWhen()管道中增加分支,條件匹配就走分支,且不切換回主分支

 Map() :

app.Map(new PathString("/test"), application => { application.Use(async (context, next) => { await context.Response.WriteAsync("test");         await next(); }); });

MapWhen():按條件執行,MapWhen比Map處理范圍更廣

app.MapWhen(context => context.Request.Path.Value.Contains("q"), application => { application.Use(async (context, next) => { await context.Response.WriteAsync("q");             await next(); }); });

UseWhen():按條件執行,與MapWhen不同的是,UseWhen執行完后切回主分支

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM