Middleware in ASP.NET Core with custom middleware

  • Middleware are components that process HTTP requests and responses in a pipeline.
  • They can perform tasks like authentication, logging, and routing.
public class MyCustomMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task Invoke(HttpContext context)
    {
        Console.WriteLine("Custom middleware before request");
        await _next(context);
        Console.WriteLine("Custom middleware after response");
    }
}

public static class MyCustomMiddlewareExtensions
{
    public static IApplicationBuilder UseMyCustomMiddleware(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<MyCustomMiddleware>();
    }
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseMyCustomMiddleware();
    app.UseRouting();
    app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
  • The Invoke method processes the request and calls the next middleware in the pipeline.
  • The extension method UseMyCustomMiddleware adds the middleware to the pipeline.

Leave a Reply

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