ASP.NET Core-注册中间件(Use、UseMiddleWare、Map、Run)

使用IApplicationBuilder注册中间件

1.Use()

app.Use(async (context, next) =>
            {
                await context.Response.WriteAsync("hello world");
                await next.Invoke();
            });


app.Use((requestDelegate) =>
            {
                return async (context) =>
                {
                    await context.Response.WriteAsync("hello world2");
                    await requestDelegate(context);
                };

            });


2.UseMiddleWare():将中间件封装,最终是使用Use注册(socket有用到)

        //自定义中间件
        public class TestMiddelware
        {
            public RequestDelegate _next;

            public TestMiddelware(RequestDelegate next)
            {
                this._next = next;
            }
            public Task Invoke(HttpContext context)
            {
                if (context.Request.Path.Value.Contains("1.jpg"))
                {
                    return context.Response.SendFileAsync("1.jpg");
                }

                if (this._next != null)
                {
                    return this._next(context);
                }
                throw new Exception("TestMiddelware error");
            }
        }


        app.UseMiddleware<TestMiddelware>(app, Array.Empty<object>());
 

3.Map()、MapWhen()管道中增加分支,条件匹配就走分支,且不切换回主分支

Map() :

app.Map(new PathString("/test"), application =>
            {
                application.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("test");
                await next();
    });
});

4.Run(RequestDelegate handler)

终结点,在管道尾端增加一个中间件,之后的中间件不再执行

app.Run(async context => {
                await context.Response.WriteAsync("hello world3");
            });

5.MapWhen():按条件执行,MapWhenMap处理范围更广

app.MapWhen(context => context.Request.Path.Value.Contains("q"), application => {
                application.Use(async (context, next) =>
                {
                    await context.Response.WriteAsync("q");
            await next();
                });
});
 

* UseWhen():按条件执行,与MapWhen不同的是,UseWhen执行完后切回主分支

  • 24
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王甜甜(.NET)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值