Published on

Middleware vs. Filter in .NET?

Authors
  • avatar
    Name
    Muhammad Mustafa
    Twitter
Middleware vs Filter

When it comes to crafting robust and efficient applications, understanding the nuances between ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ ๐—ฎ๐—ป๐—ฑ ๐—™๐—ถ๐—น๐˜๐—ฒ๐—ฟ๐˜€ can make a big difference. So let's dive into ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ ๐—ฎ๐—ป๐—ฑ ๐—™๐—ถ๐—น๐˜๐—ฒ๐—ฟ๐˜€ to uncover their roles, usage, and implementation in the pipeline!

๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ๐˜€ and ๐—™๐—ถ๐—น๐˜๐—ฒ๐—ฟ๐˜€

๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ๐˜€ ๐—”๐—ป๐—ฑ ๐—™๐—ถ๐—น๐˜๐—ฒ๐—ฟ๐˜€ act as a bridge between the HTTP request and response. It's like a series of layers that intercept, process, and potentially modify the request and response objects.

๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ spans across the entire app, while ๐—ณ๐—ถ๐—น๐˜๐—ฒ๐—ฟ๐˜€ target specific controllers or actions, offering focused enhancements where needed.

Middleware vs Filter

๐—จ๐˜€๐—ฎ๐—ด๐—ฒ ๐—ฎ๐—ป๐—ฑ ๐—ฃ๐—ผ๐˜€๐—ถ๐˜๐—ถ๐—ผ๐—ป๐—ถ๐—ป๐—ด

๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ sits in the heart of the request pipeline, It intercepts incoming requests, handling global tasks, like authentication and routing and then passes the request to the next middleware in the pipeline. Think of it as the guardian of your app's core functionality. It acts as a bridge between the client and the application.
๐—˜๐˜…๐—ฎ๐—บ๐—ฝ๐—น๐—ฒ: Authentication middleware that validates user credentials before accessing protected routes.
๐—ฃ๐—ผ๐˜€๐—ถ๐˜๐—ถ๐—ผ๐—ป: Middleware sits early in the request processing pipeline, making it ideal for tasks like logging, error handling, and authentication.

๐—œ๐—บ๐—ฝ๐—น๐—ฒ๐—บ๐—ฒ๐—ป๐˜๐—ฎ๐˜๐—ถ๐—ผ๐—ป:
To implement ๐— ๐—ถ๐—ฑ๐—ฑ๐—น๐—ฒ๐˜„๐—ฎ๐—ฟ๐—ฒ, create a class that implements the IMiddleware interface and configure it in your Startup.

using app.UseMiddleware<YourMiddlewareClass>();
Middleware Implementation

๐—™๐—ถ๐—น๐˜๐—ฒ๐—ฟ๐˜€, on the other hand, are like tailored suits for your actions, adding specific functionalities, they are applied to specific actions or controllers within the application. They enable developers to execute code before or after an action method is called, allowing for input validation, logging, and more.
๐—˜๐˜…๐—ฎ๐—บ๐—ฝ๐—น๐—ฒ: A logging filter that records detailed information about each API call.
๐—ฃ๐—ผ๐˜€๐—ถ๐˜๐—ถ๐—ผ๐—ป: Filters are applied at the action or controller level, providing granular control over behavior.

๐—œ๐—บ๐—ฝ๐—น๐—ฒ๐—บ๐—ฒ๐—ป๐˜๐—ฎ๐˜๐—ถ๐—ผ๐—ป:
For ๐—™๐—ถ๐—น๐˜๐—ฒ๐—ฟ๐˜€, decorate your controller or action methods with attributes like [Authorize], [ValidateModel], create custom filters by implementing IActionFilter, IResultFilter, etc.

Filter Implementation