Understanding Middleware in ASP.NET

What is Middleware?

Middleware is a component in ASP.NET Core applications that processes HTTP requests and responses. Middleware components are executed in a pipeline, where each component can perform operations before and after the next component is invoked.

  • Request Handling: Middleware can handle or modify incoming HTTP requests.
  • Response Handling: Middleware can generate or alter outgoing HTTP responses.
  • Pipelined Execution: Middleware components are executed in the order they are registered in the application pipeline.

How Middleware Works in ASP.NET

Middleware components are added to the HTTP request pipeline in the Program.cs file. Each middleware either processes the request and passes it to the next middleware or terminates the pipeline by sending a response.


Steps to Create and Use Middleware

Follow these steps to understand middleware with an example:

1. Create a Custom Middleware


// Middleware/RequestLoggingMiddleware.cs
public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;

    public RequestLoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        // Log the incoming request
        Console.WriteLine($"Incoming Request: {context.Request.Method} {context.Request.Path}");

        // Call the next middleware in the pipeline
        await _next(context);

        // Log the outgoing response
        Console.WriteLine($"Outgoing Response: {context.Response.StatusCode}");
    }
}

                

The RequestLoggingMiddleware logs the request method and path before calling the next middleware and logs the response status afterward.

2. Register the Middleware in Program.cs


// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// Add custom middleware
app.UseMiddleware<RequestLoggingMiddleware>();

app.MapGet("/", () => "Hello, Middleware!");

app.Run();

                

Use the UseMiddleware method to register the custom middleware in the pipeline.

3. Add Built-in Middleware


// Program.cs
app.Use(async (context, next) =>
{
    // Custom inline middleware
    Console.WriteLine("Before calling the next middleware");
    await next();
    Console.WriteLine("After calling the next middleware");
});

// Add built-in middleware
app.UseRouting();
app.UseEndpoints(endpoints =>
{
    endpoints.MapGet("/hello", () => "Hello, World!");
});

                

Built-in middleware like UseRouting and UseEndpoints can also be added to the pipeline to define routing and handle requests.

4. Middleware Execution Flow

The execution order of middleware is critical. Middleware registered earlier is executed first for incoming requests and last for outgoing responses.


// Execution flow for request pipeline
1. LoggingMiddleware logs the request
2. RoutingMiddleware routes the request
3. EndpointMiddleware handles the request
4. LoggingMiddleware logs the response

                

5. Test Middleware


// Example HTTP Request
GET /hello HTTP/1.1

// Console Output
Incoming Request: GET /hello
Before calling the next middleware
After calling the next middleware
Outgoing Response: 200

                

Observe the logs to understand how middleware components interact in the pipeline.