Courses/C#/Middleware & Filters
    Back to Course

    Lesson 32: Middleware, Filters & Custom Attributes in ASP.NET

    Intercept and transform HTTP requests with middleware pipelines, action filters, and custom attributes.

    What You'll Learn

    • • Custom middleware for logging, timing, and error handling
    • • Action, result, and exception filters
    • • Custom attributes for API keys and rate limiting
    • • Middleware pipeline ordering and its importance

    🧠 Real-World Analogy

    Middleware is like airport security checkpoints. Every request (passenger) passes through them in order: ticket check → security scan → passport control → boarding. Each checkpoint can stop the request, modify it, or let it through. The order matters — you can't board before security.

    Custom Middleware

    Middleware sits in the HTTP pipeline and processes every request. Each middleware component calls _next(context) to pass the request to the next component. Code before _next runs on the request; code after runs on the response. Order matters — exception handling must come first.

    Custom Middleware — Timing & Error Handling

    Build middleware that times requests and catches unhandled exceptions.

    Try it Yourself »
    C#
    // Middleware — intercepts every HTTP request/response
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Http;
    using System.Diagnostics;
    
    // Custom middleware class
    public class RequestTimingMiddleware
    {
        private readonly RequestDelegate _next;
        
        public RequestTimingMiddleware(RequestDelegate next) => _next = next;
        
        public async Task InvokeAsync(HttpContext context)
        {
            var stopwatch = Stopwatch.StartNew();
            
            // Add a request ID for tracing
    ...

    Action Filters

    Filters are more targeted than middleware — they run only for specific controllers or actions. ASP.NET provides four filter types: Authorization, Action, Result, and Exception filters. They're ideal for cross-cutting concerns that don't apply to every request.

    Action, Result & Exception Filters

    Log actions, add response headers, and handle specific exceptions with filters.

    Try it Yourself »
    C#
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    
    // Action Filter — runs before/after controller actions
    public class LogActionFilter : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext context)
        {
            var action = context.ActionDescriptor.DisplayName;
            var args = string.Join(", ", context.ActionArguments
                .Select(kv => $"{kv.Key}={kv.Value}"));
            Console.WriteLine($"  🔵 Before: {action}({args})");
        }
        
        publ
    ...

    Custom Attributes

    Custom attributes combine filter logic with declarative syntax. Decorate controllers or actions with [RequireApiKey] or [RateLimit(10, 60)] to add security and throttling without cluttering business logic.

    Custom Attributes — API Key & Rate Limiting

    Build reusable attribute-based security and rate limiting.

    Try it Yourself »
    C#
    using System;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.Filters;
    
    // Custom attribute that validates API keys
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class RequireApiKeyAttribute : Attribute, IAuthorizationFilter
    {
        private const string API_KEY_HEADER = "X-Api-Key";
        
        public void OnAuthorization(AuthorizationFilterContext context)
        {
            if (!context.HttpContext.Request.Headers
                .TryGetValue(API_KEY_HEADER, out va
    ...
    ConceptScopeUse For
    MiddlewareEvery requestLogging, CORS, compression, auth
    Action FilterSpecific controllers/actionsValidation, audit logging
    Exception FilterSpecific controllers/actionsDomain-specific error handling
    Custom AttributeDeclarative (any target)API keys, rate limits, caching

    Pro Tip

    Use IEndpointFilter in Minimal APIs for the same functionality as action filters in controllers. They support DI and async, making them very flexible.

    Common Mistakes

    • • Placing exception middleware after UseAuthorization — errors in auth won't be caught
    • • Using scoped services in middleware constructor — use InvokeAsync parameters instead
    • • Forgetting to call _next(context) — request gets stuck

    Lesson Complete!

    You've mastered ASP.NET middleware, filters, and custom attributes. Next, dive into Entity Framework Core internals.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy PolicyTerms of Service