š 3 Ways to Create Middleware in ASP.NET Core
ASP.NET Core includes many essential middleware components to help you manage requests, security, and diagnostics.
Middleware plays a central role in ASP.NET Core's request processing pipeline. Whether you're building APIs, web apps, or microservices, mastering middleware helps you add cross-cutting behavior like logging, authentication, or exception handlingācleanly and efficiently.
In this post, Iāll walk you through three different ways to create middleware in ASP.NET Core, along with when to use each approach and best practices to follow.
š§© What is Middleware?
Middleware is a software component that intercepts HTTP requests and responses in the ASP.NET Core pipeline. It can inspect, modify, or short-circuit a request, or simply pass it on to the next middleware in line.
Common tasks handled by middleware:
ā Logging
š Authentication / Authorization
ā Error Handling
š Routing
š Static File Serving
Each piece of middleware is invoked in sequence, and can either:
Perform a task and pass control to the next middleware
Or, end the pipeline and return a response immediately
š” Benefits of Middleware in ASP.NET Core
Modular Design ā Clean separation of concerns
Flexible Pipeline ā Reorder components easily
Reusability ā Use across multiple apps
Cross-Cutting Concern Handling ā Keep logic DRY and centralized
āļø 1. Inline Middleware (Delegate-Based)
The simplest way to create middleware is inline, using a delegate with the Use
method.
ā
When to Use
For quick prototyping
Simple logic that doesn't need reuse
app.Use(async (context, next) =>
{
Console.WriteLine("Request handled by inline middleware");
await next(); // Call next middleware
});
š Tip: Great for small cross-cutting behaviors or quick diagnostics, but avoid placing complex logic here.
š§± 2. Convention-Based Middleware (Class-Based)
Convention-based middleware involves creating a class that has a constructor and an Invoke
or InvokeAsync
method.
š How it Works
ASP.NET Core scans for a specific pattern:
public class MyMiddleware
{
private readonly RequestDelegate _next;
public MyMiddleware(RequestDelegate next) => _next = next;
public async Task InvokeAsync(HttpContext context)
{
// Your logic here
await _next(context); // Call next middleware
}
}
And register it like this:
app.UseMiddleware<MyMiddleware>();
ā
When to Use
Reusable logic
Middleware that requires constructor injection (e.g., ILogger)
š Tip: This is the most widely used approach due to its simplicity and power.
š§Ŗ 3. Factory-Based Middleware (IMiddleware)
Factory-based middleware uses dependency injection fully and implements the IMiddleware
interface.
public class MyMiddleware : IMiddleware
{
public async Task InvokeAsync(HttpContext context, RequestDelegate next)
{
// Logic here
await next(context);
}
}
Register it in Program.cs
:
builder.Services.AddTransient<MyMiddleware>();
app.UseMiddleware<MyMiddleware>();
ā
When to Use
For middleware that needs scoped services
Better control over lifetime management (transient/scoped/singleton)
š Tip: Use this approach when you want to rely on DI container lifetimes or manage middleware instances per request.
š Common Built-In Middleware in ASP.NET Core
1. UseRouting()
Enables endpoint routing.
Matches the incoming request to a route.
app.UseRouting();
2. UseAuthentication()
Checks if the request has a valid identity (e.g., JWT, cookies).
app.UseAuthentication();
3. UseAuthorization()
Verifies if the authenticated user has permission to access the resource.
app.UseAuthorization();
4. UseExceptionHandler()
Global exception handling middleware.
Can redirect to an error page or return a formatted JSON error.
app.UseExceptionHandler("/Home/Error");
5. UseStaticFiles()
Serves static files like HTML, CSS, JS, images from the
wwwroot
folder.
app.UseStaticFiles();
6. UseHttpsRedirection()
Automatically redirects HTTP requests to HTTPS.
app.UseHttpsRedirection();
7. UseCors()
Handles Cross-Origin Resource Sharing (CORS) policies.
app.UseCors("MyPolicy");
8. UseEndpoints()
Final part of the routing process, where the matched route is executed.
csharp
š§ Final Thoughts
Middleware is a powerful abstraction in ASP.NET Core. Whether you're logging requests, handling errors, or injecting custom logic, understanding how to write and structure middleware can drastically improve the maintainability and performance of your applications.
š GitHub Example
š Full working code available at:
š https://github.com/KanaiyaKatarmal/middleware
I hope you found this guide helpful and informative.
Thanks for reading!
If you enjoyed this article, feel free to share it and follow me for more practical, developer-friendly content like this.