;

Middleware vs. Filters in .NET Core


Tutorialsrack 23/02/2025 C# ASP.NET Core

Introduction

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.

What is Middleware?

Definition

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.

How Middleware Works

Middleware components are executed in a pipeline where they can either process requests and pass them further or short-circuit the pipeline.

Example: Creating a Simple Middleware

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();

What are Filters?

Definition

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.

Types of Filters in .NET Core

  1. Authorization Filters - Handles authentication and authorization.
  2. Resource Filters - Executes before and after model binding.
  3. Action Filters - Executes before and after an action method.
  4. Exception Filters - Handles exceptions.
  5. Result Filters - Executes before and after returning a result.

Example: Creating a Custom Action Filter

public class CustomActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext context)
    {
        Console.WriteLine("Action Executing");
    }

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        Console.WriteLine("Action Executed");
    }
}

Applying the Filter to a Controller

[CustomActionFilter]
public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }
}

Key Differences Between Middleware and Filters

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

Detailed Examples with Explanations

Example: Using Middleware for Logging

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);
    }
}

Example: Using Filters for Authorization

public class CustomAuthorizationFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (!context.HttpContext.User.Identity.IsAuthenticated)
        {
            context.Result = new UnauthorizedResult();
        }
    }
}

Real-World Applications

When to Use Middleware

  • Global exception handling
  • Logging and diagnostics
  • Authentication and authorization checks
  • CORS configuration

When to Use Filters

  • Validating model state before execution
  • Handling specific controller or action logic
  • Custom authorization checks at the controller level

Key Takeaways

  • Middleware is used for global request processing, while Filters are used at the controller/action level.
  • Middleware is best suited for cross-cutting concerns affecting all requests.
  • Filters are best used for concerns specific to MVC controllers and actions.
  • Understanding the right use case for each improves application maintainability and performance.

Summary

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!


Related Posts



Comments

Recent Posts
Tags