ASP.NET Core处理管道的深入理解
// 最终的处理函数 RequestDelegate app = context => { context.Output.AppendLine("End of output."); return Task.CompletedTask; }; // 定义中间件 1 Func<RequestDelegate, RequestDelegate> middleware1 = next => { return (HttpContextSample context) => { // 中间件 1 的处理内容 context.Output.AppendLine("Middleware 1 Processing."); // 调用后继的处理函数 return next(context); }; }; // 得到一个有一个处理步骤的管道 var pipeline1 = middleware1(app); // 准备一个表示当前请求的对象 var context2 = new HttpContextSample(); // 通过管道处理当前请求 pipeline1(context2); // 输出请求的处理结果 Console.WriteLine(context2.Output.ToString()); 可以得到如下的输出 Middleware 1 Processing. 继续增加第二个中间件来演示多个中间件的级联处理。 RequestDelegate app = context => { context.Output.AppendLine("End of output."); return Task.CompletedTask; }; // 定义中间件 1 Func<RequestDelegate, RequestDelegate> middleware1 = next => { return (HttpContextSample context) => { // 中间件 1 的处理内容 context.Output.AppendLine("Middleware 1 Processing."); // 调用后继的处理函数 return next(context); }; }; // 定义中间件 2 Func<RequestDelegate, RequestDelegate> middleware2 = next => { return (HttpContextSample context) => { // 中间件 2 的处理 context.Output.AppendLine("Middleware 2 Processing."); // 调用后继的处理函数 return next(context); }; }; // 构建处理管道 var step1 = middleware1(app); var pipeline2 = middleware2(step1); // 准备当前的请求对象 var context3 = new HttpContextSample(); // 处理请求 pipeline2(context3); // 输出处理结果 Console.WriteLine(context3.Output.ToString()); 当前的输出 Middleware 2 Processing. 如果我们把这些中间件保存到几个列表中,就可以通过循环来构建处理管道。下面的示例重复使用了前面定义的 app 变量。 List<Func<RequestDelegate, RequestDelegate>> _components = new List<Func<RequestDelegate, RequestDelegate>>(); _components.Add(middleware1); _components.Add(middleware2); // 构建处理管道 foreach (var component in _components) { app = component(app); } // 构建请求上下文对象 var context4 = new HttpContextSample(); // 使用处理管道处理请求 app(context4); // 输出处理结果 Console.WriteLine(context4.Output.ToString()); 输出结果与上一示例完全相同 Middleware 2 Processing. 但是,有一个问题,我们后加入到列表中的中间件 2 是先执行的,而先加入到列表中的中间件 1 是后执行的。如果希望实际的执行顺序与加入的顺序一致,只需要将这个列表再反转一下即可。 (编辑:西安站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |