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();
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.

Privacy Overview
Referbruv

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

3rd Party Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.