public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.Use(next => { return async context => { await context.Response.WriteAsync("A11111111</br>"); await next.Invoke(context); //下一中间件 await context.Response.WriteAsync("B11111111</br>"); }; }); app.Use(next => { return async context => { await context.Response.WriteAsync("A22222222</br>"); await next.Invoke(context); //下一中间件 await context.Response.WriteAsync("B22222222</br>"); }; }); app.Use(next => { return async context => { await context.Response.WriteAsync("A33333333</br>"); await context.Response.WriteAsync("B33333333</br>"); }; }); }
运行的时候是先执行3->2->1 倒序
自己动手构建RequestDelegate管道
class Program { static void Main(string[] args) { ApplicationBuilder app = new ApplicationBuilder(); app.Use(next => { return async context => { await context.WriteAsync("A11111111 "); await next.Invoke(context); //下一中间件 await context.WriteAsync("B11111111 "); }; }); app.Use(next => { return async context => { await context.WriteAsync("A22222222 "); await next.Invoke(context); //下一中间件 await context.WriteAsync("B22222222 "); }; }); app.Use(next => { return async context => { await context.WriteAsync("A33333333 "); await context.WriteAsync("B33333333 "); }; }); var requestDelegate = app.Build(); requestDelegate.Invoke(new HttpContext()); Console.ReadLine(); } public delegate Task RequestDelegate(HttpContext context); public class HttpContext { public async Task WriteAsync(string text) { Console.WriteLine(text); await Task.CompletedTask; } } public class ApplicationBuilder { public List<Func<RequestDelegate, RequestDelegate>> _list = new List<Func<RequestDelegate, RequestDelegate>>(); RequestDelegate requestDelegate = new RequestDelegate(async context => { Console.WriteLine("404 "); await Task.CompletedTask; }); public RequestDelegate Build() { _list.Reverse(); foreach (var func in _list) { requestDelegate = func.Invoke(requestDelegate); } return requestDelegate; } public ApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware) { this._list.Add(middleware); return this; } } }