ASP.NET Core Middleware: A Complete Guide

ASP.NET Core is a high-performance, cross-platform web framework developed by Microsoft. One of its most powerful and flexible features is middleware, which plays a central role in handling HTTP requests and responses in the application pipeline. In this article, we'll explore:

  1. What is middleware is
  2. How the How Middleware Works
  3. How to create custom middleware
  4. Middleware Orders

ASP.NET Core Middleware: A Complete Guide

Getting Started

Middleware is one of the most powerful features in ASP.NET Core. It enables a clean, pluggable, and modular way of handling HTTP requests. Whether you're serving static files, authenticating users, logging, or modifying responses — middleware is where it happens.

In ASP.NET Core, middleware is software that's assembled into an application pipeline to handle requests and responses. You can say middleware in .net core is a sequence of plumbing stpes where each step can modify the request, produce a response, or both. Some middleware might short-circuit the pipeline without calling the next step. For example, a middleware can return an error or service a static file.

What is Middleware In .Net Core?

Middleware in .Net Core is a key concept in request processing pipeline. It is a software that is executed in sequence to handle HTTP requests and responses as part of a pipeline. Each middleware component in the pipeline has a specific purpose and can

  • Receives an HTTP request.
  • Optionally calls the next middleware in the pipeline
  • Or modify the request/response before or after the next component runs.

How Middleware Works

Each middleware component:
  1. Performs some operations before calling the next middleware (e.g., authentication, logging).
  2. Optionally calls the next middleware via await next();.
  3. Performs some operations after the next middleware has run (e.g., response modification).
If one middleware does not call next(), it short-circuits the pipeline.

Common Purposes of Middleware In ASP.Net.Core

  • Logging
  • Exception handling
  • Request/response modification
  • CORS handling
  • Security (authentication, authorization)
  • Performance metrics

Common Built-in ASP.NET Core Middleware Components

ASP.NET Core provides several built-in middleware components, some of the middlewares are listed below:

  1. UseStaticFiles(): Serves static files like CSS, JS, images
  2. UseRouting(): Enables routing for endpoints
  3. UseAuthentication(): Authentication middleware in net.core validates user identity
  4. UseAuthorization():Authorization middleware in net.core Checks access permissions
  5. UseCors(): Enables Cross-Origin Resource Sharing
  6. UseExceptionHandler(): Handles unhandled exceptions globally
  7. UseHttpsRedirection(): Redirects HTTP requests to HTTPS

Custom Middleware In .Net.Core

You can create your own middleware for tasks like logging, request modification, or error handling. Custom middleware in .Net Core can be written as inline delegates, but for cleaner and reusable code, it is good practice to create a dedicated class.

Create a Custome Middleware

The below code example is a custom middleware is created for loggin in ASP.NET Core application.

public class LoggingMiddleware  
 {  
   private readonly RequestDelegate _next;  
   public LoggingMiddleware(RequestDelegate next)  
   {  
     _next = next;  
   }  
   public async Task InvokeAsync(HttpContext context)  
   {  
     Console.WriteLine($"Incoming request: {context.Request.Method} {context.Request.Path}");  
     await _next(context); // Call the next middleware  
     Console.WriteLine($"Response status: {context.Response.StatusCode}");  
   }  
 }  

Registering Custome Middleware
app.UseMiddleware<LoggingMiddleware>(); 

Middleware Order

In ASP.NET Core, middleware order refers to the sequence in which middleware components are added to the HTTP request pipeline — and therefore, the order in which they handle incoming requests and outgoing responses.

This order is critical, because each middleware can:
  • Handle a request (and optionally stop further processing), or
  • Pass it to the next middleware in the pipeline.

Typical Recommended Order
Order Middleware Purpose
1 UseExceptionHandler / UseDeveloperExceptionPage Handle errors globally
2 UseHsts / UseHttpsRedirection Security
3 UseStaticFiles Serve static content
4 UseRouting Adds routing to the pipeline
5 UseCors Cross-Origin Resource Sharing
6 UseAuthentication Validate user credentials
7 UseAuthorization Enforce access policies
8 UseSession Manage session state
9 UseEndpoints / MapControllers / MapRazorPages Execute endpoints

Example: Middleware Order in Program.cs
 var builder = WebApplication.CreateBuilder(args);  
 var app = builder.Build();  
 // 1. Exception handling (should come early)  
 app.UseExceptionHandler("/Home/Error");  
 // 2. HTTPS redirection  
 app.UseHttpsRedirection();  
 // 3. Static files  
 app.UseStaticFiles();  
 // 4. Routing  
 app.UseRouting();  
 // 5. Authentication  
 app.UseAuthentication();  
 // 6. Authorization  
 app.UseAuthorization();  
 // 7. Endpoint mapping (final)  
 app.MapControllers();  
 app.Run();  

Visualization
 Request -->  
  [Exception Handling]  
   [HTTPS Redirection]  
    [Static Files]  
     [Routing]  
      [Authentication]  
       [Authorization]  
        [Endpoint Execution]  
 Response <--  

Each middleware wraps the next one, forming a nested pipeline. If you want to know how middleware ordering works, why it matters, and best practices to ensure your ASP.NET Core pipeline runs smoothly then visit my post Making Middleware Order Right in ASP.NET Core.

Summary

Middleware in ASP.NET Core provides a powerful way to compose the behavior of your application. By understanding how middleware works and how to write your own, you gain fine-grained control over the HTTP pipeline, making your application more modular, testable, and maintainable. I hope this was helpful to you

Thanks

Kailash Chandra Behera

I am an IT professional with over 13 years of experience in the full software development life cycle for Windows, services, and web-based applications using Microsoft .NET technologies.

Previous Post Next Post

نموذج الاتصال