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

使用IApplicationBuilder注册中间件

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);
                };

            });

UseMiddleWare():将中间件封装,最终是使用Use注册

        //自定义中间件
        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>());

Run(RequestDelegate handler)

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

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

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

Map() :

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

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执行完后切回主分支

猜你喜欢

转载自blog.csdn.net/WuLex/article/details/111664980