Middleware is a component in ASP.NET Core applications that processes HTTP requests and responses. Middleware components are executed in a pipeline, where each component can perform operations before and after the next component is invoked.
Middleware components are added to the HTTP request pipeline in the Program.cs
file. Each middleware either processes the request and passes it to the next middleware or terminates the pipeline by sending a response.
Follow these steps to understand middleware with an example:
// Middleware/RequestLoggingMiddleware.cs
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
public RequestLoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext context)
{
// Log the incoming request
Console.WriteLine($"Incoming Request: {context.Request.Method} {context.Request.Path}");
// Call the next middleware in the pipeline
await _next(context);
// Log the outgoing response
Console.WriteLine($"Outgoing Response: {context.Response.StatusCode}");
}
}
The RequestLoggingMiddleware
logs the request method and path before calling the next middleware and logs the response status afterward.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Add custom middleware
app.UseMiddleware<RequestLoggingMiddleware>();
app.MapGet("/", () => "Hello, Middleware!");
app.Run();
Use the UseMiddleware
method to register the custom middleware in the pipeline.
// Program.cs
app.Use(async (context, next) =>
{
// Custom inline middleware
Console.WriteLine("Before calling the next middleware");
await next();
Console.WriteLine("After calling the next middleware");
});
// Add built-in middleware
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/hello", () => "Hello, World!");
});
Built-in middleware like UseRouting
and UseEndpoints
can also be added to the pipeline to define routing and handle requests.
The execution order of middleware is critical. Middleware registered earlier is executed first for incoming requests and last for outgoing responses.
// Execution flow for request pipeline
1. LoggingMiddleware logs the request
2. RoutingMiddleware routes the request
3. EndpointMiddleware handles the request
4. LoggingMiddleware logs the response
// Example HTTP Request
GET /hello HTTP/1.1
// Console Output
Incoming Request: GET /hello
Before calling the next middleware
After calling the next middleware
Outgoing Response: 200
Observe the logs to understand how middleware components interact in the pipeline.