What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.Run() C# Asp.net Core?

CsharpServer Side ProgrammingProgramming

We can configure middleware in the Configure method of the Startup class using IApplicationBuilder instance.

Run() is an extension method on IApplicationBuilder instance which adds a terminal middleware to the application's request pipeline.

The Run method is an extension method on IApplicationBuilder and accepts a parameter of RequestDelegate.

signature of the Run method

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

signature of RequestDelegate

public delegate Task RequestDelegate(HttpContext context);

Example

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..
   }
}

The above MyMiddleware function is not asynchronous and so will block the thread till the time it completes the execution. So, make it asynchronous by using async and await to improve performance and scalability.

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

Configure Multiple Middleware using Run()

The following will always execute the first Run method and will never reach the second Run method

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

To configure multiple middleware, use Use() extension method. It is similar to Run() method except that it includes next parameter to invoke next middleware in the sequence

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");
   });
}
raja
Published on 24-Sep-2020 16:41:25
Advertisements