在 C# Asp.net Core 中,IApplicationBuilder.Use() 和 IApplicationBuilder.Run() 之間有什麼區別?


我們可以在 Startup 類的 Configure 方法中使用 IApplicationBuilder 例項配置中介軟體。

Run() 是 IApplicationBuilder 例項上的一個擴充套件方法,它嚮應用程式的請求管道新增一個終端中介軟體。

Run 方法是 IApplicationBuilder 上的一個擴充套件方法,並接受一個 RequestDelegate 型別的引數。

Run 方法的簽名

public static void Run(this IApplicationBuilder app, RequestDelegate handler)

RequestDelegate 的簽名

public delegate Task RequestDelegate(HttpContext context);

示例

public class Startup{
   public Startup(){
   }
   public void Configure(IApplicationBuilder app, IHostingEnvironment env,
   ILoggerFactory loggerFactory){
      //configure middleware using IApplicationBuilder here..
      app.Run(async (context) =>{
         await context.Response.WriteAsync("Hello World!");
      });
      // other code removed for clarity..
   }
}

上面的 MyMiddleware 函式不是非同步的,因此會在執行完成之前阻塞執行緒。因此,使用 async 和 await 使其非同步以提高效能和可擴充套件性。

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

使用 Run() 配置多箇中間件

以下將始終執行第一個 Run 方法,並且永遠不會到達第二個 Run 方法

public void Configure(IApplicationBuilder app, IHostingEnvironment env){
   app.Run(async (context) =>{
      await context.Response.WriteAsync("1st Middleware");
   });
   // the following will never be executed
   app.Run(async (context) =>{
      await context.Response.WriteAsync(" 2nd Middleware");
   });
}

USE

要配置多箇中間件,請使用 Use() 擴充套件方法。它類似於 Run() 方法,但它包括 next 引數以按順序呼叫下一個中介軟體

public void Configure(IApplicationBuilder app, IHostingEnvironment env){
   app.Use(async (context, next) =>{
      await context.Response.WriteAsync("1st Middleware!");
      await next();
   });
   app.Run(async (context) =>{
      await context.Response.WriteAsync("2nd Middleware");
   });
}

更新於: 2020-09-24

5K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.