HTTP Message Handlers in ASP.NET Web API

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 : HTTP Message Handlers in ASP.NET Web API

I am using delegating handler with Refit API so its registration looks like this : HTTP Message Handlers in ASP.NET Web API

You can register custom HttpClient like this if you are not using Refit HTTP Message Handlers in ASP.NET Web API

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 .

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