Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่างระหว่าง IApplicationBuilder.Use() และ IApplicationBuilder.Run() ใน C# ASP.NET Core

เราสามารถกำหนดค่า Middleware ในเมธอด Configure ของคลาส Startup โดยใช้อินสแตนซ์ IApplicationBuilder

Run()

Run() เป็น Extension Method บนอินสแตนซ์ IApplicationBuilder ซึ่งเพิ่ม Terminal Middleware เข้าไปใน Request Pipeline ของแอปพลิเคชัน เมธอด Run เป็น Extension Method บน IApplicationBuilder และรับพารามิเตอร์ประเภท RequestDelegate

// Signature ของ Run method
public static void Run(this IApplicationBuilder app, RequestDelegate handler)

// Signature ของ RequestDelegate
public delegate Task RequestDelegate(HttpContext context);

ตัวอย่างการใช้ Run()

public class Startup {
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
        app.Run(async (context) => {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

โค้ดด้านบนไม่ใช่ Asynchronous จะบล็อก Thread จนกว่าจะทำงานเสร็จ ควรใช้ async และ await เพื่อปรับปรุงประสิทธิภาพและความสามารถในการขยายระบบ

public class Startup {
    public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
        app.Run(MyMiddleware);
    }
    
    private async Task MyMiddleware(HttpContext context) {
        await context.Response.WriteAsync("Hello World!");
    }
}

การกำหนดค่า Multiple Middleware ด้วย Run()

โค้ดต่อไปนี้จะ Execute เมธอด Run แรกเสมอ และจะไม่ถึงเมธอด Run ที่สองเลย

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    app.Run(async (context) => {
        await context.Response.WriteAsync("1st Middleware");
    });
    // โค้ดด้านล่างจะไม่ถูก Execute לעולם
    app.Run(async (context) => {
        await context.Response.WriteAsync("2nd Middleware");
    });
}

Use()

เพื่อกำหนดค่า Multiple Middleware ให้ใช้ Extension Method Use() คล้ายกับ Run() แต่แตกต่างตรงที่มีพารามิเตอร์ next เพื่อเรียก Middleware ถัดไปในลำดับ

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
    app.Use(async (context, next) => {
        await context.Response.WriteAsync("1st Middleware!");
        await next(); // เรียก Middleware ถัดไป
    });
    
    app.Run(async (context) => {
        await context.Response.WriteAsync("2nd Middleware");
    });
}

สรุปความแตกต่าง

คุณสมบัติRun()Use()
ประเภท MiddlewareTerminal (จุดสิ้นสุด)Inline (กลาง)
พารามิเตอร์RequestDelegate (context)Func<HttpContext, Func<Task>, Task> (context, next)
การเรียก Middleware ถัดไปไม่สามารถทำได้ต้องเรียก await next() เอง
จำนวนที่ใช้ได้เพียงตัวสุดท้ายเท่านั้นหลายตัวติดต่อกันได้