Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

IApplicationBuilder.Use()와 IApplicationBuilder.Run() C# Asp.net Core의 차이점은 무엇입니까?

<시간/>

IApplicationBuilder 인스턴스를 사용하여 Startup 클래스의 Configure 메소드에서 미들웨어를 구성할 수 있습니다.

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 andawait를 사용하여 비동기화하여 성능과 확장성을 향상시키십시오.

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() 확장 메소드를 사용하십시오. 이 시퀀스에서 다음 미들웨어를 호출하는 다음 매개변수를 포함한다는 점을 제외하면 Run() 메서드와 유사합니다.

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