| Muhammad Waseem

About Newsletter
Books
30 .NET Tips
Sponsorship
HTTP Message Handlers in ASP.NET Web API
Oct 21, 2023
3 min read

HTTP Message Handlers in ASP.NET Web API

Sponsor this Newsletter

Delegating handler introduction

A message handler is a class that receives an HTTP request and returns an HTTP response. Message handlers derive from the abstract HttpMessageHandler class.

So it look something like this :

HTTP Message Handlers in ASP.NET Web API

For what purposes we can use it

We can use it for various purposes:

  • Caching
  • Logging
  • Error Handling
  • Custom Headers
  • Throttling and Rate Limiting
  • Compression/Decompression
  • Authentication and Authorization
  • Request/Response Transformation

How to use it in ASP .NET Web API

It is quite simple to use it , these are the steps:

1/ Create your handler class and inherit it from DelegatingHandler which comes from System.Net.Http.DelegatingHandler

2/ Override its SendAsync method, and implement your logic.

3/ Register your handler in services.

Let’s see it via code :

public sealed class LoggingHandler : DelegatingHandler
{
    private readonly ILogger<LoggingHandler> _logger;

    public LoggingHandler(ILogger<LoggingHandler> logger)
    {
        _logger = logger;
    }

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Request: {Method} {RequestUri}", request.Method, request.RequestUri);

        var response = await base.SendAsync(request, cancellationToken);

        _logger.LogInformation("Response: {StatusCode}", response.StatusCode);

        return response;
    }
}

I am using delegating handler with Refit API so its registration looks like this :

// Registering the LoggingHandler as a scoped service
builder.Services.AddScoped<LoggingHandler>();

// TODO: The best approach is to read the base address from appsettings.json
builder.Services.AddRefitClient<IDogsAPI>()
   .ConfigureHttpClient(client => client.BaseAddress = new Uri("some-api"))
   .AddHttpMessageHandler<LoggingHandler>();

// Registering the DogsService as a scoped service
builder.Services.AddScoped<IDogsService, DogsService>();

You can register custom HttpClient like this if you are not using Refit

services.AddTransient<CustomHandler>();
services.AddHttpClient("some-client", c =>
{
 c.BaseAddress = new Uri("some-address");
})
.AddHttpMessageHandler<CustomHandler>();

How is delegating handler different than middleware

Both middleware and delegating handler serve same purpose, they can can intercept the request and response.

Both can do short circuit and we can chain multiple delegate handler similar to middlewares.

In my opinion it is choosing right thing for right action, if you have to play with HttpClient and do some updates with request/response then delegate handlers are best choice.

GitHub Demo Code

Get demo code of this newsletter issue at my GitHub Repo

This article was originally published at https://mwaseemzakir.substack.com/ on Oct 21, 2023 .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place
Previous Next

Subscribe to Newsletter

Join 9,000 Software Engineers

Buy Me a Coffee

Enjoy my articles? Support me by buying a coffee!

Buy Me a Coffee

Muhammad Waseem

Resources
  • Books
  • Courses
Newsletter
  • Articles
  • Sponsorship
Books
  • 30 .NET Tips
  • 100 .NET Tips (Soon)
Author
  • About Us
  • Contact Us
Policy
  • Privacy Policy
  • Terms and Conditions
Interview
  • C# & .NET
  • Web API

Join my .NET newsletter and stay updated!

© 2025 Muhammad Waseem. All rights reserved.