Middleware vs DelegatingHandler in ASP.NET Core – Complete Guide

Middleware vs DelegatingHandler in ASP.NET Core, When building ASP.NET Core applications, developers often get confused between Middleware and DelegatingHandler.
Both intercept requests, both can modify headers, and both can handle cross-cutting concerns — but they operate in completely different pipelines.

In this guide, you’ll learn:

  • What Middleware is and how it works
  • What DelegatingHandler is and where it executes
  • Key differences between Middleware vs DelegatingHandler
  • Real-world use cases and best practices

What Is Middleware in ASP.NET Core?

Middleware is a component that sits in the ASP.NET Core request pipeline and handles incoming HTTP requests and outgoing responses.

Common Middleware Responsibilities

  • Exception handling
  • Authentication & authorization
  • Logging & diagnostics
  • CORS
  • Request/response manipulation

Middleware Example

public class LoggingMiddleware
{
    private readonly RequestDelegate _next;

    public LoggingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        Console.WriteLine($"Request: {context.Request.Path}");
        await _next(context);
        Console.WriteLine($"Response: {context.Response.StatusCode}");
    }
}

Register Middleware

app.UseMiddleware<LoggingMiddleware>();

What Is DelegatingHandler in ASP.NET Core?

DelegatingHandler is part of the HttpClient pipeline and is used to handle outgoing HTTP requests.

It does not handle incoming requests to your API.


DelegatingHandler Example

public class LoggingDelegatingHandler : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        Console.WriteLine($"Outgoing request: {request.RequestUri}");
        return await base.SendAsync(request, cancellationToken);
    }
}

Register DelegatingHandler

builder.Services.AddHttpClient("MyClient")
    .AddHttpMessageHandler<LoggingDelegatingHandler>();

Key Differences: Middleware vs DelegatingHandler

FeatureMiddlewareDelegatingHandler
PipelineASP.NET Core request pipelineHttpClient pipeline
DirectionIncoming & outgoingOutgoing only
ScopeEntire applicationPer HttpClient
Access to HttpContext✅ Yes❌ No
Access to HttpRequestMessage❌ No✅ Yes
Typical UseAPIs, MVC, RazorExternal API calls

Execution Flow Comparison

Middleware Flow

Client Request → Middleware → Controller → Middleware → Client Response

DelegatingHandler Flow

API → HttpClient → DelegatingHandler → External API → Response

When to Use Middleware?

✔ Handle incoming requests
✔ Global exception handling
✔ Authentication, authorization
✔ Request/response logging


When to Use DelegatingHandler?

✔ Handle outgoing HTTP calls
✔ Add authentication headers (Bearer, API keys)
✔ Retry policies, correlation IDs
✔ Logging external API calls


Can Middleware Replace DelegatingHandler?

No

They serve different purposes:

  • Middleware → Server-side request handling
  • DelegatingHandler → Client-side HTTP calls

Using one in place of the other is an architectural mistake.


Real-World Example (Best Practice)

Scenario:
Your API receives a request, then calls an external service.

✔ Middleware
→ Validate user, log request, handle exceptions

✔ DelegatingHandler
→ Add JWT token, log outgoing request, retry on failure


Interview Question (Very Common)

Q: What is the difference between Middleware and DelegatingHandler?

Answer:
Middleware handles incoming HTTP requests in the ASP.NET Core pipeline, while DelegatingHandler handles outgoing HTTP requests in the HttpClient pipeline.


Conclusion

Middleware vs DelegatingHandler in ASP.NET Core, Middleware and DelegatingHandler may look similar, but they operate in different layers of ASP.NET Core.

📌 Quick Rule

  • Incoming requests → Middleware
  • Outgoing HTTP calls → DelegatingHandler

Read our detailed guides on Request Pipeline – Complete Execution & Middleware vs Filters in detail.

Explore more important concepts here…

1 thought on “Middleware vs DelegatingHandler in ASP.NET Core – Complete Guide”

  1. Pingback: Exception Handling in ASP.NET Core - Complete Guide - Mika Dev Hub

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top