ASP.NET Core Middleware: Complete Beginner Guide

Middleware is one of the most important concepts in ASP.NET Core. Every HTTP request and response passes through a middleware pipeline before reaching your application endpoints.

Understanding middleware helps developers build secure, scalable, and maintainable web applications. Whether you're creating an MVC application, Web API, or Razor Pages project, middleware plays a critical role in processing requests.

In this tutorial, you'll learn how middleware works, how to create custom middleware, and how to use built-in ASP.NET Core middleware components effectively.


Topics Covered
  • What is Middleware?
  • How the Request Pipeline Works
  • Built-in Middleware
  • Creating Custom Middleware
  • Dependency Injection
  • Middleware Ordering
  • Common Use Cases
  • Best Practices

What Is Middleware?

Middleware is software that sits between an incoming HTTP request and the application's final endpoint.

Each middleware component can:

  • Process incoming requests.
  • Perform actions before passing the request forward.
  • Call the next middleware in the pipeline.
  • Modify outgoing responses.
  • Terminate the request if necessary.

Middleware components are executed in the order they are registered in the application pipeline.

Understanding the Request Pipeline

Every request enters the middleware pipeline and travels through multiple components.


        Browser Request
        ↓
        Routing Middleware
        ↓
        Authentication Middleware
        ↓
        Authorization Middleware
        ↓
        Controller / Endpoint
        ↓
        Response Returned
    

The order of middleware registration directly affects how requests are processed.

Middleware in Program.cs

Middleware is typically configured inside Program.cs.


        var app = builder.Build();

        app.UseHttpsRedirection();

        app.UseStaticFiles();

        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.MapControllers();

        app.Run();
    

Each Use method adds a middleware component to the pipeline.

Common Built-in Middleware Components

Middleware Purpose
UseHttpsRedirection Redirect HTTP traffic to HTTPS.
UseStaticFiles Serve CSS, JavaScript, and images.
UseRouting Enable endpoint routing.
UseAuthentication Authenticate users.
UseAuthorization Apply authorization policies.
UseCors Handle cross-origin requests.

Using Run Middleware

The Run method terminates the middleware pipeline.


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

Any middleware registered after Run will never execute.

Using Use Middleware

The Use method allows middleware to call the next component.


        app.Use(async (context, next) =>
        {
        Console.WriteLine("Before Request");

        await next();

        Console.WriteLine("After Request");
        });
    

This middleware executes both before and after the next middleware.

Creating Custom Middleware

Custom middleware lets you implement application-specific behavior.

Step 1: Create Middleware Class


        public class RequestLoggingMiddleware
        {
        private readonly RequestDelegate _next;

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

        public async Task InvokeAsync(
        HttpContext context)
        {
        Console.WriteLine(
        $"Request Path: {context.Request.Path}");

        await _next(context);
        }
        }
    

Step 2: Register Middleware


        app.UseMiddleware
        <RequestLoggingMiddleware>();
    

The custom middleware will now execute for every request.

Middleware with Dependency Injection

Middleware can receive services from ASP.NET Core's Dependency Injection container.


        public class LoggingMiddleware
        {
        private readonly RequestDelegate _next;
        private readonly ILogger<LoggingMiddleware> _logger;

        public LoggingMiddleware(
        RequestDelegate next,
        ILogger<LoggingMiddleware> logger)
        {
        _next = next;
        _logger = logger;
        }

        public async Task InvokeAsync(
        HttpContext context)
        {
        _logger.LogInformation(
        "Request received.");

        await _next(context);
        }
        }
    

Middleware Ordering Matters

Incorrect middleware ordering is a common beginner mistake.

Correct Order


        app.UseRouting();

        app.UseAuthentication();

        app.UseAuthorization();

        app.MapControllers();
    

Authentication should occur before authorization because users must be identified before permissions can be checked.

Exception Handling Middleware

ASP.NET Core includes built-in exception handling middleware.


        if (!app.Environment.IsDevelopment())
        {
        app.UseExceptionHandler("/Home/Error");
        }
    

This prevents sensitive exception details from being exposed in production environments.

Static File Middleware


        app.UseStaticFiles();
    

This middleware serves files from the wwwroot folder, including CSS, JavaScript, images, and fonts.

HTTPS Redirection Middleware


        app.UseHttpsRedirection();
    

Redirecting HTTP traffic to HTTPS improves security and helps protect user data during transmission.

CORS Middleware

Cross-Origin Resource Sharing (CORS) allows web applications to access resources from different domains.


        app.UseCors(policy =>
        {
        policy.AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader();
        });
    

CORS is especially important when building Web APIs.

Common Middleware Use Cases

  • Request logging.
  • Authentication.
  • Authorization.
  • Error handling.
  • Response compression.
  • Security headers.
  • Performance monitoring.
  • Request validation.

Best Practices

  • Keep middleware focused on a single responsibility.
  • Register middleware in the correct order.
  • Use built-in middleware whenever possible.
  • Avoid expensive operations inside middleware.
  • Log important requests and errors.
  • Use Dependency Injection for external services.

Common Mistakes

  • Incorrect middleware ordering.
  • Forgetting to call next().
  • Adding unnecessary middleware.
  • Exposing sensitive information in logs.
  • Performing heavy database operations in middleware.

Frequently Asked Questions

What is middleware in ASP.NET Core?

Middleware is software that processes HTTP requests and responses within the ASP.NET Core request pipeline.

Can middleware modify responses?

Yes. Middleware can inspect and modify both requests and responses.

Why is middleware order important?

Middleware executes sequentially. Incorrect ordering can break authentication, routing, authorization, and other features.

Should I create custom middleware?

Custom middleware is useful when you need functionality that is not provided by ASP.NET Core's built-in components.

Related Tutorials

Conclusion

Middleware forms the foundation of every ASP.NET Core application. Understanding how the request pipeline works allows developers to build more secure, maintainable, and scalable web applications.

By mastering built-in middleware and learning how to create custom middleware, you'll be able to handle logging, security, routing, authentication, error handling, and many other essential tasks within your ASP.NET Core projects.