Custom Middleware in ASP.NET Core

Custom Middleware in ASP.NET Core
ASP.NET Core provides a plethora of built-in middleware components, sometimes you need to create your own to address specific requirements unique to your application. Custom middleware allows you to:
Encapsulate logic: Bundle related operations (e.g., logging, security checks, custom headers) into a reusable component.
Customize behavior: Tailor the request/response pipeline to precisely match your application’s needs.
Improve code organization: Keep your middleware code clean and maintainable.
 
Anatomy of a Custom Middleware Class
Implement IMiddleware: This interface requires a single method: InvokeAsync(HttpContext context, RequestDelegate next). This is the heart of your middleware’s logic.
InvokeAsync or Invoke Method:
context: The HttpContext provides access to the request and response objects.
next: The RequestDelegate allows you to call the next middleware in the pipeline.
 
Code Explanation
Let’s dissect the code you provided:
// MyCustomMiddleware.cs
namespace MiddlewareExample.CustomMiddleware
{
    public class MyCustomMiddleware : IMiddleware 
    {
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            await context.Response.WriteAsync(“My Custom Middleware – Starts\n”);
            await next(context); 
            await context.Response.WriteAsync(“My Custom Middleware – Ends\n”);
        }
    }
 
    // Extension method for easy registration
    public static class CustomMiddlewareExtension
    {
        public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder app)
        {
            return app.UseMiddleware<MyCustomMiddleware>();
        }
    }
}
 
MyCustomMiddleware Class: This class implements IMiddleware. Its InvokeAsync method:
Writes “My Custom Middleware – Starts” to the response.
Calls next(context) to invoke the next middleware in the pipeline.
Writes “My Custom Middleware – Ends” to the response after the next middleware has finished.
CustomMiddlewareExtension Class: This provides a convenient extension method UseMyCustomMiddleware to register your middleware in the Startup.Configure method.
 
// Program.cs (or Startup.cs)
using MiddlewareExample.CustomMiddleware;
 
// …
 
builder.Services.AddTransient<MyCustomMiddleware>(); // Register as transient
 
app.Use(async (HttpContext context, RequestDelegate next) => {
    await context.Response.WriteAsync(“From Midleware 1\n”);
    await next(context);
});
 
app.UseMyCustomMiddleware(); // Use the extension method
 
app.Run(async (HttpContext context) => {
    await context.Response.WriteAsync(“From Middleware 3\n”);
});

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply