We can configure the middleware in the Configure method of the Startup class, using IApplicationBuilder instance.
Run() is an extension method on the IApplicationBuilder instance, which adds a terminal
Add middleware to the application's request pipeline.
The Run method is an extension method of IApplicationBuilder and accepts a
Parameters of RequestDelegate.
Run method signature
public static void Run(this IApplicationBuilder app, RequestDelegate handler)
RequestDelegate signature
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.. } }
The above MyMiddleware function is not asynchronous, so it will block the thread until it completes execution. So by using async and Wait 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! "); } }
Configuring multiple middleware using Run()
The following code will always execute the first Run method and will never reach
The second Run methodpublic 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"); }); }
To configure multiple middleware, use the Use() extension method. It is similar to Run() method, except that it contains the next parameter to call the next middleware 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"); }); }
The above is the detailed content of What is the difference between IApplicationBuilder.Use() and IApplicationBuilder.Run() C# Asp.net Core?. For more information, please follow other related articles on the PHP Chinese website!