Short-Circuiting Demo in Middleware of core (Part 4)

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.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.