net core 中间件(MiddleWare)

it2022-05-05  219

定义:中间件是被组装成一个应用程序管道来处理请求和响应的软件组件。

上图是由微软提供的一个执行图,我们可以看到有多个中间件,每个中间件请求的时候有个next()方法把职责传递给下一个中间件,这里值得注意的是最后一个中间件没有next方法,也就是终止,然后响应。

每一个中间件都有它自己的职责,把各个执行分离开执行完成后传递给下一个,直到全部的都执行完成,这有点像职责链模式。那么它内部是怎么实现的呢,下面我们看看

值得注意的是,StartUp类里面包含两个方法,ConfigureServices是专门负责容器,Configure是负责http管道方法,所以中间件实在configure方法里面的。

我们来看看IApplicationBuilder这个里面有什么

如上图所示,我们在使用Use的时候,传入的中间件添加到委托上,传入和返回的都是一个RequestDelegate类型的,当我们进入这个方法的时候,发现它是携带HttpContext的

 Use、Run 和 Map介绍

Use:上面我们可以看到他里面传入的是一个Request Delegate的委托方法,里面有一个Next()传递给下一个中间件的方法,如果该方法不执行,那么下面的中间件也是不会执行的,我们称之为短路中间件。

Run:是一种约定,并且某些中间件组件可公开在管道末尾运行的 Run[Middleware] 方法。

Map:扩展用作约定来创建管道分支。 Map* 基于给定请求路径的匹配项来创建请求管道分支。 如果请求路径以给定路径开头,则执行分支。

下面我们来看看短路中间件

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.Use(async (context,next)=> { await context.Response.WriteAsync("use\n"); //await next.Invoke(); }); app.Run(async (context) => { await context.Response.WriteAsync("run"); }); }

我们来自定义一个中间件

//这是我们的中间件 public class UseTestMiddleWare { private readonly RequestDelegate _next; public UseTestMiddleWare(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { await context.Response.WriteAsync("invoke\n"); await _next.Invoke(context); } } //我们需要把中间件添加到扩展里面才能使用它 public static class UseTestMiddleWareExtensions { public static IApplicationBuilder UseTestMiddleWare(this IApplicationBuilder builder) { return builder.UseMiddleware<UseTestMiddleWare>(); } }

调用:

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseTestMiddleWare(); app.Run(async context => { await context.Response.WriteAsync("hello"); }); }

 


最新回复(0)