Create a Custom Middleware in ASP.NET Core

Introduction

Custom middleware in ASP.NET Core allows you to add custom logic to the request and response pipeline. Middleware components are executed in the order they are added, providing a flexible way to handle cross-cutting concerns, such as logging, authentication, and more. Here’s how you can create and use custom middleware in ASP.NET Core:

Step 1: Create a Custom Middleware Class

Create a new class for your custom middleware. A middleware component must have a constructor that takes a RequestDelegate parameter, which represents the next delegate in the pipeline. Here’s an example of a custom middleware that logs the request path:

using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;

public class RequestLoggingMiddleware
{
    private readonly RequestDelegate _next;
    private readonly ILogger<RequestLoggingMiddleware> _logger;

    public RequestLoggingMiddleware(RequestDelegate next, ILogger<RequestLoggingMiddleware> logger)
    {
        _next = next;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        _logger.LogInformation($"Request path: {context.Request.Path}");
        await _next(context);
    }
}

Step 2: Register Custom Middleware

In the Startup.cs file, add the following code to the Configure method to register and use your custom middleware:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
        app.UseHsts();
    }

    app.UseMiddleware<RequestLoggingMiddleware>(); // Register custom middleware

    app.UseHttpsRedirection();
    app.UseStaticFiles();
    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

Step 3: Test Custom Middleware

Run your ASP.NET Core application, and the custom middleware will log the request path for each incoming request. You can further customize the middleware to perform any additional actions or checks based on your requirements.

Note: Middleware components are executed in the order they are added using the Use method. Be cautious about the order of middleware registration to ensure proper execution flow.

Custom middleware allows you to inject your own logic into the request/response pipeline, enabling you to handle cross-cutting concerns or implement specific functionality that is not already provided by built-in middleware. This approach provides a clean and modular way to extend the behavior of your ASP.NET Core application.

Leave a Reply

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