As the name suggesting short-circuiting means breaking the flow of execution before the destination in middleware.
As shown in the above example, if we have to break the follow of execution in middleware we have implement the short-circuiting functionality. We can do it by just removing the next() method in the middleware.
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using System.Diagnostics; namespace MiddleWare_Sample { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { //Middleware A app.Use(async (context, next) => { Debug.WriteLine("A (before)"); await next(); Debug.WriteLine("A (after)"); }); // Middleware B app.Use(async (context, next) => { Debug.WriteLine("B (before)"); //await next(); await context.Response.WriteAsync("This is the end of execution of middleware B"); Debug.WriteLine("B (after)"); }); // Middleware C (terminal) app.Run(async context => { Debug.WriteLine("C (end MiddleWare in pipeline)"); await context.Response.WriteAsync("Hello world"); }); } } }
As shown in the above code, after commenting on next() method, middleware end terminal is not executing. It is breaking the flow before the end terminal. If we will get scenario to short-circuiting in middleware we can achieve like this.