Tool for HR, Hiring Managers, and the Leadership Team

Middleware in ASP.NET Core

1. What is Middleware in ASP.NET Core?

Middleware in .NET Core is a piece of code that handles HTTP requests and responses in the application's request pipeline.

Think of Middleware like pipeline steps 

When a request comes:

Request → Middleware 1 → Middleware 2 → Middleware 3 → Response

Each middleware can:

  • Handle the request

  • Modify the request

  • Pass to next middleware

  • Stop the pipeline

Example Built-in Middleware

.NET Core has many built-in middleware:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints();

Pipeline flow:

Request
 ↓
UseRouting
 ↓
UseAuthentication
 ↓
UseAuthorization
 ↓
UseEndpoints
 ↓
Response

Real Example

Suppose user calls:

https://example.com/api/users

Middleware pipeline:

Request
 ↓
Logging Middleware
 ↓
Authentication Middleware
 ↓
Authorization Middleware
 ↓
Controller
 ↓
Response

2. Can we create Custom Middleware?

✅ Yes, we can create custom middleware in .NET Core

There are 2 ways:

Method 1 (Recommended) — Class Based Middleware

Step 1: Create Middleware Class

public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        Console.WriteLine("Before Request");

        await _next(context);

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

Step 2: Register Middleware

app.UseMiddleware<MyCustomMiddleware>();

Method 2 — Inline Middleware

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

    await next();

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

Example Output

If user calls API:

Before Request
Controller Executed
After Response

When to Use Custom Middleware

Use middleware for:

✅ Logging
✅ Exception Handling
✅ Authentication
✅ Performance Tracking
✅ Request Validation
✅ Response Modification

Interview Tip 

Short Interview Answer

Middleware is software component in .NET Core that handles HTTP requests and responses in the request pipeline. We can create custom middleware using RequestDelegate and register it using app.UseMiddleware()

Common Interview Follow-ups

They may ask:

  • What is RequestDelegate?

  • Difference between Use, Run, Map?

  • Middleware execution order?

  • Can middleware short-circuit?