Middleware in ASP.NET Core processes HTTP requests and responses in a pipeline. While ASP.NET provides built-in middleware, you can create custom middleware to handle specific application requirements, such as logging, authentication, or modifying responses.
Follow these steps to create and use custom middleware in an ASP.NET Core application:
// Middleware/CustomHeaderMiddleware.cs
public class CustomHeaderMiddleware
{
private readonly RequestDelegate _next;
public CustomHeaderMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Before the next middleware
Console.WriteLine("Custom middleware executing before the next middleware.");
// Call the next middleware
await _next(context);
// After the next middleware
context.Response.Headers.Add("X-Custom-Header", "MiddlewareDemo");
Console.WriteLine("Custom middleware executing after the next middleware.");
}
}
The CustomHeaderMiddleware
adds a custom HTTP response header and logs messages during request and response processing.
// Extensions/MiddlewareExtensions.cs
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseCustomHeaderMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomHeaderMiddleware>();
}
}
The extension method UseCustomHeaderMiddleware
makes it easier to add the middleware to the request pipeline.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Add custom middleware
app.UseCustomHeaderMiddleware();
app.MapGet("/", () => "Welcome to Custom Middleware Demo!");
app.Run();
Use the extension method to add the middleware to the pipeline.
// Example Request
GET / HTTP/1.1
// Example Response
HTTP/1.1 200 OK
X-Custom-Header: MiddlewareDemo
Content-Type: text/plain; charset=utf-8
Welcome to Custom Middleware Demo!
Observe the response header X-Custom-Header
to verify that the custom middleware executed correctly.