Filters

Back

Loading concept...

🎬 ASP.NET Filters: The Security Guards of Your Web App

Imagine a movie theater with different checkpoints. Before you watch the movie, guards check your ticket, your bag, and make sure you’re not bringing in outside food. ASP.NET Filters work the same wayβ€”they’re checkpoints that run before, during, or after your code does its job!


🌟 What Are Filters?

Think of your web app as a theme park. Visitors (requests) want to ride the roller coasters (your actions). But before they can ride, they pass through checkpoints:

  • 🎫 Ticket checker (checks if allowed in)
  • πŸŽ’ Bag inspector (prepares things)
  • 🚨 Emergency responder (handles problems)
  • πŸ“Έ Photo booth (adds finishing touches)

Filters are these checkpoints! They run automatically at specific moments without you calling them directly.


🎯 The Filter Family: 4 Types

graph TD A["Request Arrives"] --> B["πŸ”’ Resource Filter"] B --> C["⚑ Action Filter"] C --> D["Your Code Runs"] D --> E["πŸ“¦ Result Filter"] E --> F["Response Sent"] D -->|Error!| G["🚨 Exception Filter"] G --> F

1️⃣ Action Filters: The Before & After Guards

Simple Idea: Action filters run right before and right after your main code (action) runs.

πŸŽͺ Real-Life Example

Like a referee in a soccer game:

  • Before the play: β€œEveryone ready? Go!”
  • After the play: β€œThat was a goal!”

πŸ“ Code Example

public class LogActionFilter : IActionFilter
{
    public void OnActionExecuting(
        ActionExecutingContext context)
    {
        // BEFORE: Log when action starts
        Console.WriteLine("Action starting!");
    }

    public void OnActionExecuted(
        ActionExecutedContext context)
    {
        // AFTER: Log when action ends
        Console.WriteLine("Action finished!");
    }
}

🎯 When to Use

  • βœ… Logging who visited what page
  • βœ… Validating input data
  • βœ… Timing how long actions take

2️⃣ Exception Filters: The Emergency Handlers

Simple Idea: When something goes BOOM πŸ’₯ (an error), exception filters catch it and handle it gracefully.

πŸŽͺ Real-Life Example

Like a safety net under trapeze artists. If they fall, the net catches them safely!

πŸ“ Code Example

public class HandleErrorFilter : IExceptionFilter
{
    public void OnException(
        ExceptionContext context)
    {
        // Catch the error
        var error = context.Exception.Message;

        // Show friendly message instead
        context.Result = new ObjectResult(
            new { error = "Oops! Something broke." }
        );

        // Mark as handled
        context.ExceptionHandled = true;
    }
}

🎯 When to Use

  • βœ… Showing friendly error pages
  • βœ… Logging errors for developers
  • βœ… Sending error alerts

3️⃣ Result Filters: The Final Touch Artists

Simple Idea: Result filters run right before and right after the result (response) is created.

πŸŽͺ Real-Life Example

Like a gift wrapper at a store. Your gift (data) is ready, but they add the pretty bow (extra formatting)!

πŸ“ Code Example

public class AddHeaderFilter : IResultFilter
{
    public void OnResultExecuting(
        ResultExecutingContext context)
    {
        // BEFORE result: Add custom header
        context.HttpContext.Response.Headers
            .Add("X-Custom", "Hello!");
    }

    public void OnResultExecuted(
        ResultExecutedContext context)
    {
        // AFTER result: Log it was sent
        Console.WriteLine("Result sent!");
    }
}

🎯 When to Use

  • βœ… Adding response headers
  • βœ… Modifying the final output
  • βœ… Caching responses

4️⃣ Resource Filters: The First & Last Checkpoint

Simple Idea: Resource filters run first (before everything) and last (after everything). They wrap the entire process!

πŸŽͺ Real-Life Example

Like the main gate of a castle. You pass through it first when entering and last when leaving!

πŸ“ Code Example

public class CacheFilter : IResourceFilter
{
    public void OnResourceExecuting(
        ResourceExecutingContext context)
    {
        // FIRST: Check if we have cached result
        var cached = GetFromCache(context);
        if (cached != null)
        {
            // Skip everything, return cached!
            context.Result = cached;
        }
    }

    public void OnResourceExecuted(
        ResourceExecutedContext context)
    {
        // LAST: Save to cache for next time
        SaveToCache(context.Result);
    }
}

🎯 When to Use

  • βœ… Caching (save and reuse results)
  • βœ… Short-circuiting (skip everything if needed)
  • βœ… Resource management

πŸ› οΈ Creating Custom Filters

Making your own filter is like building your own checkpoint!

🎯 Three Ways to Create

Way 1: Implement Interface

public class MyFilter : IActionFilter
{
    public void OnActionExecuting(...) { }
    public void OnActionExecuted(...) { }
}

Way 2: Inherit from Attribute

public class MyFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(
        ActionExecutingContext context)
    {
        // Your logic here
    }
}

Way 3: Use It Anywhere!

// On a single action
[MyFilter]
public IActionResult GetData() { }

// On a whole controller
[MyFilter]
public class HomeController { }

// On ALL controllers (global)
services.AddControllers(options =>
{
    options.Filters.Add<MyFilter>();
});

βš–οΈ Filters vs Middleware: What’s the Difference?

Both are checkpoints, but they work at different levels!

graph TD A["Request"] --> B["Middleware 1"] B --> C["Middleware 2"] C --> D["Routing"] D --> E["🎯 Filters Start Here"] E --> F["Your Controller"] F --> G["Response"]

πŸ• Pizza Shop Analogy

Middleware Filters
πŸͺ The building entrance πŸ• The kitchen area
Checks ALL visitors Checks only customers ordering pizza
Runs for every request Runs only for controller actions
No access to action details Knows which action is running

πŸ“Š Quick Comparison

Feature Middleware Filters
Scope All requests Controller actions only
Order Runs first Runs after routing
Access Basic HTTP Full MVC context
Use For Logging, Auth, CORS Validation, Caching

🎯 When to Use What?

Use Middleware When:

  • βœ… Logging all requests
  • βœ… Authentication for whole app
  • βœ… Adding headers to all responses

Use Filters When:

  • βœ… Validating action parameters
  • βœ… Handling action-specific errors
  • βœ… Caching specific actions

πŸ”„ The Complete Flow

Here’s how everything runs in order:

graph TD A["πŸ“₯ Request"] --> B["Middleware Chain"] B --> C["Routing"] C --> D["πŸ”’ Resource Filter - Before"] D --> E["⚑ Action Filter - Before"] E --> F["🎬 Your Action"] F --> G["⚑ Action Filter - After"] G --> H["πŸ“¦ Result Filter - Before"] H --> I["Result Executes"] I --> J["πŸ“¦ Result Filter - After"] J --> K["πŸ”’ Resource Filter - After"] K --> L["πŸ“€ Response"] F -->|Error!| M["🚨 Exception Filter"] M --> K

πŸŽ‰ You Did It!

Now you understand ASP.NET Filters! Remember:

Filter Type When It Runs Think Of It As
Resource First & Last Castle gate
Action Before & After action Referee
Exception When errors happen Safety net
Result Before & After result Gift wrapper

πŸ’‘ Pro Tip: Filters keep your controller code clean. Instead of repeating the same checks in every action, create a filter once and use it everywhere!


Next up: Try building your own filter in the Interactive Lab! πŸš€

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.