In .NET Core, both Middleware and Filters play an essential role in handling HTTP requests and responses. However, they serve different purposes and are applied at different stages of request processing. Understanding their differences can help developers decide when to use Middleware and when to use Filters effectively.
This article provides a step-by-step guide to Middleware and Filters, explaining their functionalities with practical examples.
Middleware in .NET Core is software that is executed on every request and response. It allows developers to handle cross-cutting concerns like authentication, logging, exception handling, and request modification.
Middleware components are executed in a pipeline where they can either process requests and pass them further or short-circuit the pipeline.
public class CustomMiddleware
{
private readonly RequestDelegate _next;
public CustomMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
Console.WriteLine("Custom Middleware Executing");
await _next(context);
Console.WriteLine("Custom Middleware Executed");
}
}
Registering Middleware in Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.UseMiddleware<CustomMiddleware>();
app.Run();
Filters in .NET Core are used specifically in the MVC pipeline to handle cross-cutting concerns at the controller or action level, such as validation, authorization, and exception handling.
public class CustomActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
Console.WriteLine("Action Executing");
}
public override void OnActionExecuted(ActionExecutedContext context)
{
Console.WriteLine("Action Executed");
}
}
[CustomActionFilter]
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
}
Feature |
Middleware |
Filters |
Scope |
Global (entire app) |
Specific to MVC requests |
Execution |
Runs in request pipeline |
Runs in MVC action pipeline |
Usage |
Authentication, logging, CORS |
Validation, authorization, exception handling |
Application |
Applied to all requests |
Applied at controller/action level |
public class LoggingMiddleware
{
private readonly RequestDelegate _next;
public LoggingMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
Console.WriteLine("Logging Request: " + context.Request.Path);
await _next(context);
}
}
public class CustomAuthorizationFilter : IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
if (!context.HttpContext.User.Identity.IsAuthenticated)
{
context.Result = new UnauthorizedResult();
}
}
}
Middleware and Filters in .NET Core serve distinct but complementary roles. Middleware provides a mechanism for handling global concerns like logging, authentication, and error handling, while Filters allow more fine-grained control over MVC request processing. By using them effectively, developers can build scalable and maintainable applications.
Now that you understand Middleware vs. Filters in .NET Core, try implementing them in your projects for better request handling and performance!
Comments