Custom and Using Middleware in .NET CORE

To use and customize a middleware, you need to ensure two things:

  • The middleware class must declare a public constructor with at least one parameter of type RequestDelegate. This is the reference to the next middleware in the pipeline. When you call this RequestDelegate you are actually calling the next middleware in the pipeline.

  • The middleware class must define a public method named Invoke that takes an HttpContext and returns a Task. This is the method that is called when the request reaches the middleware.

public class CustomeMiddleware
    {
        private readonly RequestDelegate _next;
 
        public CustomeMiddleware(RequestDelegate next)
        {
            _next = next;
        }
 
        public async System.Threading.Tasks.Task Invoke(HttpContext context)
        {
            await context.Response.WriteAsync("<div> before - CustomeMiddleware </div>");
            await _next(context);
            await context.Response.WriteAsync("<div> after - CustomeMiddleware </div>");
        }
    }

In the constructor, we will get the reference of the next middleware in the pipeline. We store it in a local variable named _next

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

Finally, we need to register the middleware in the request pipeline. We can use the UseMiddleware method in the Startup.cs file as shown below:

app.UseMiddleware<SimpleMiddleware>();

Last updated