流浪のwolf

卷帝

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

如何使用中间件

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

 ps:中间件的注册顺序很重要 ;

posted on   朱龙旭的网络  阅读(28)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· Blazor Hybrid适配到HarmonyOS系统
· 支付宝 IoT 设备入门宝典(下)设备经营篇
· 万字调研——AI生成内容检测
· 解决跨域问题的这6种方案,真香!
· 一套基于 Material Design 规范实现的 Blazor 和 Razor 通用组件库
点击右上角即可分享
微信分享提示