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():条件付き実行、幅広であるMapWhenよりもMap処理範囲

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
おすすめ