🔹 What is Middleware in ASP.NET Core?

In ASP.NET Core, a middleware is a component that is executed for every HTTP request that enters the application. Middleware components form the backbone of the request-processing pipeline.

In traditional ASP.NET, similar roles were played by HttpHandlers and HttpModules. However, middleware in ASP.NET Core offers a more modular, flexible, and testable approach to handling requests and responses.

Each middleware in the pipeline can:

  • Handle the request.

  • Modify the request or response.

  • Pass control to the next middleware in the sequence.

Middleware can be:

  • Built-in (provided by the framework).

  • Installed via NuGet packages.

  • Custom components you write yourself.

The order in which middleware is added in the Startup.cs file is crucial, as it defines the execution flow.


🔸 Middleware Execution Flow

Here’s a simplified flow of how middleware components work in sequence:

  1. Request comes in.

  2. Passes through each middleware in the order they are added.

  3. A middleware can:

    • Perform actions before the next component.

    • Call the next middleware.

    • Perform actions after the next component has finished.

  4. Response flows back through the middleware stack in reverse order.


🔸 Example of Middleware in ASP.NET Core

    {
        public void Configure(IApplicationBuilder app)
        {
            app.Use(async (context, next) =>
            {
                Console.WriteLine("Middleware 1 - Before");
                await next.Invoke();
                Console.WriteLine("Middleware 1 - After");
            });

            app.Use(async (context, next) =>
            {
                Console.WriteLine("Middleware 2 - Before");
                await next.Invoke();
                Console.WriteLine("Middleware 2 - After");
            });

            app.Run(async (context) =>
            {
                Console.WriteLine("Final Middleware (Terminal)");
                await context.Response.WriteAsync("Hello from ASP.NET Core!");
            });
        }
    }

🔸 Output:
    Middleware 1 - Before
    Middleware 2 - Before
    Final Middleware (Terminal)
    Middleware 2 - After
    Middleware 1 - After




Leave a Reply

Your email address will not be published. Required fields are marked *


Talk to us?

Post your blog

F.A.Q

Frequently Asked Questions