ASP.NET Core Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

Middleware in ASP.NET Core

Back to: ASP.NET Core Tutorial

Middleware in ASP.NET Core is a fundamental concept used to build the HTTP request pipeline. Each middleware component in the pipeline:

  • Processes incoming HTTP requests.

  • Optionally short-circuits the pipeline (e.g., for authentication).

  • Passes control to the next middleware.

  • Optionally processes the outgoing HTTP response.


What is Middleware?

Middleware is software that's assembled into an application pipeline to handle requests and responses. Each component:

  • Can perform work before and after the next delegate (middleware) is invoked.

  • Can terminate the request pipeline early.

  • Can perform asynchronous operations.


Request Pipeline Structure

Here’s a simple visualization:


HTTP Request --> Middleware 1 --> Middleware 2 --> Middleware 3 --> ...
| Controller/Endpoint |
<-- Middleware 3 <-- Middleware 2 <-- Middleware 1
HTTP Response


Middleware Lifecycle

Each middleware is a RequestDelegate:


csharp
public delegate Task RequestDelegate(HttpContext context);


Creating Custom Middleware

You can create custom middleware by either:

1. Class-based Middleware

public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Pre-processing logic
Console.WriteLine("Request: " + context.Request.Path);
await _next(context);
// Call the next middleware
// Post-processing logic
Console.WriteLine("Response: " + context.Response.StatusCode);
}
}

Register it in Startup.cs:


csharp
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware();
}

2. Inline Middleware (Lambda)

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


Built-in Middleware Examples

ASP.NET Core includes many built-in middleware components:

Middleware Description
UseStaticFiles Serves static files like images, JS, CSS
UseRouting Routes requests to endpoints
UseAuthentication Authenticates the user
UseAuthorization Authorizes access based on policies/roles
UseEndpoints Maps endpoints to controllers or Razor pages
UseExceptionHandler Global exception handling
UseHttpsRedirection Redirects HTTP requests to HTTPS
UseCors Configures Cross-Origin Resource Sharing (CORS)
UseSession Enables session state

Order Matters

The order of middleware registration in Configure() is critical. For example:

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

Putting UseAuthentication() after UseEndpoints() would result in no authentication.


Best Practices

  • Keep middleware focused on one responsibility.

  • Handle exceptions early in the pipeline.

  • Use inline middleware for short logic, classes for complex logic.

  • Avoid long blocking operations – use async/await.

Scroll to Top