Middleware de registro de ASP.NET Core (Use, UseMiddleWare, Map, Run)

Usar IApplicationBuildermiddleware registrado

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(): Encapsula el middleware y finalmente usa el Useregistro.

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

Punto final, agregue un middleware al final de la canalización y el middleware posterior ya no se ejecutará

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

Map()、MapWhen()Agregue ramas a la tubería, bifurque si la condición coincide y no vuelva a la rama principal

Map() :

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

MapWhen(): Ejecutar condicionalmente, que es más amplio MapWhenque el Maprango de procesamiento

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

UseWhen(): Ejecutar condicionalmente, la MapWhendiferencia es que UseWhenvuelve a la rama principal después de la ejecución

Supongo que te gusta

Origin blog.csdn.net/WuLex/article/details/111664980
Recomendado
Clasificación