1.21 中间件:掌控请求处理过程的关键.pdf
- Map vs MapWhen
- Use 与 Run 的区别
if (env.IsDevelopment()){ app.UseDeveloperExceptionPage();}app.Use(async (context, next) =>{ //await context.Response.WriteAsync("Hello"); await next(); // 判断是否已经开始向响应的 body 输出内容 if (context.Response.HasStarted) { // 一旦已经开始输出,则不能再修改响应头的内容 } await context.Response.WriteAsync("Hello2");});// 对特定路径指定中间件app.Map("/abc", abcBuilder =>{ abcBuilder.Use(async (context, next) => { //await context.Response.WriteAsync("Hello"); await next(); await context.Response.WriteAsync("Hello2"); });});// 对特定条件指定中间件app.MapWhen(context =>{ return context.Request.Query.Keys.Contains("abc");}, builder =>{ // 与 Use 不同。 // Use 里面可以接 next 继续执行后续中间件 // Run 表示中间件执行的末端,不再执行后面的中间件 builder.Run(async context => { await context.Response.WriteAsync("new abc"); });});app.UseMyMiddleware();app.UseHttpsRedirection();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>{ endpoints.MapControllers();});