Explain how to configure a Middleware in ASP.NET Core?

Middlewares are custom components that encapsulate specific functionality and execute during a request pipeline in an ASP.NET Core web application

What is a Middleware?

A Middleware component is a custom component that encapsulates a specific functionality and executes during a request pipeline in an ASP.NET Core web application. A Middleware replaces a HttpModule and a HttpHandler of the .NET Framework in .NET Core.

A logical component (a class or a method) can be configured into a middleware by registering it under the Configure() method of the Startup class. It can be done as below.

How to configure a Middleware?

Logically, there are 3 ways in which you can configure a custom Middleware in an ASP.NET Core application.

Inline Middleware Definition

Takes a constructor parameter of RequestDelegate and uses it to navigate to next component, or a simple method delegate within the Configure method as below.

app.Use(async (context, next) =>
{
    // Custom middleware logic
    await context.Response.WriteAsync("Hello from Inline Middleware!\n");
    
    // Call the next middleware in the pipeline
    await next();
});

Custom Middleware Class

If the logic to be implemented is complex or involves multiple services to be injected, we can create a custom class that encapsulates all the logic and register as a middleware – using the UseMiddleware generic method where the type of the middleware class is passed.

public class MyHelloMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        // Custom middleware logic
        await context.Response.WriteAsync("Hello from Middleware Class!\n");

        // Call the next middleware in the pipeline
        await _next(context);
    }
}

// In the Configure method
app.UseMiddleware<MyHelloMiddleware>();

Using Extension Method

You can further extend this by creating a separate extension method over the IApplicationBuilder interface and then calling the method directly.

public class MyHelloMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        // Custom middleware logic
        await context.Response.WriteAsync("Hello from Middleware Class!\n");

        // Call the next middleware in the pipeline
        await _next(context);
    }
}

public static class CustomMiddlewareExtensions
{
    public static IApplicationBuilder UseHello(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyHelloMiddleware>();
    }
}

// In the Configure method
app.UseHello();

Buy Me A Coffee

Found this article helpful? Please consider supporting!

Ram
Ram

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity. You can connect with me on Medium, Twitter or LinkedIn.

Leave a Reply

Your email address will not be published. Required fields are marked *