Middleware is a crucial component in ASP.NET Core applications that allows developers to handle requests and responses efficiently. It provides a way to build modular, reusable components that can execute logic before or after processing an HTTP request.
In this post, we'll explore what middleware is, how it works, and how to create custom middleware components. We'll also look at built-in middleware and real-world examples.
Middleware in .NET Core is software that is executed on every request made to an application. It can:
Middleware components are configured in the Program.cs
file (or Startup.cs
in older .NET Core versions) within the request pipeline:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.Use(async (context, next) =>
{
Console.WriteLine("Incoming request: " + context.Request.Path);
await next.Invoke();
Console.WriteLine("Outgoing response: " + context.Response.StatusCode);
});
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello, Middleware!");
});
app.Run();
This middleware logs request and response details before forwarding the request.
Middleware components are executed in the order they are registered. Each middleware can:
Request -> Middleware 1 -> Middleware 2 -> Middleware 3 -> Response
If a middleware terminates the request, the remaining components will not execute.
You can create custom middleware as an inline delegate, a separate class, or an extension method.
app.Use(async (context, next) =>
{
Console.WriteLine("Custom Middleware Executed");
await next.Invoke();
});
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
Console.WriteLine("Request handled by custom middleware");
await _next(context);
}
}
Register the middleware in Program.cs
:
app.UseMiddleware<CustomMiddleware>();
ASP.NET Core provides many built-in middleware components, including:
Example of using built-in middleware:
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseStaticFiles();
Logging is essential for tracking request data.
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
public LoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
Console.WriteLine($"Request Path: {context.Request.Path}");
await _next(context);
}
}
Register it:
app.UseMiddleware<LoggingMiddleware>();
Middleware can handle JWT authentication:
app.UseAuthentication();
To handle global exceptions:
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500;
await context.Response.WriteAsync("An error occurred!");
});
});
Mastering middleware in .NET Core is crucial for building scalable and maintainable applications. Whether using built-in middleware or developing custom middleware, understanding its role in the request pipeline ensures better performance and security.
Now, try creating custom middleware components in your .NET Core applications and see how they improve request handling!
Comments