1. 注册
var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.Map("/test", async appbuilder => { appbuilder.Use(async (context, next) => { context.Response.ContentType = "text/html"; await context.Response.WriteAsync("1 Start<br/>"); await next.Invoke(); await context.Response.WriteAsync("1 End<br/>"); }); appbuilder.Use(async (context, next) => { await context.Response.WriteAsync("2 Start<br/>"); await next.Invoke(); await context.Response.WriteAsync("2 End<br/>"); });
// 用文件形式的中间件引入
appbuilder.UseMiddleware<TestMiddleware>();
appbuilder.Run(async ctx => { await ctx.Response.WriteAsync("hello middleware <br/>"); }); }); app.Run();
TestMiddleWare中间件中的具体实现 :
namespace 中间件 { public class TestMiddleware { private readonly RequestDelegate next; public TestMiddleware(RequestDelegate next) { this.next = next; } public async Task InvokeAsync(HttpContext context) { context.Response.WriteAsync("测试中间件开始"); await next.Invoke(context); context.Response.WriteAsync("测试中间件结束"); } } }
标签:WriteAsync,await,中间件,next,如何,context,使用,Response From: https://www.cnblogs.com/zhulongxu/p/17796097.html