如何使用中间件

发布时间 2023-10-29 17:36:12作者: 流浪のwolf

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("测试中间件结束");
        }
    }
}