About today’s newsletter :
In today’s newsletter we are going to discuss:
What is delegating handler
For what purposes we can use it
How to use it in ASP .NET Web API
How is it different than middleware
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 :
For what purposes we can use it
We can use it for various purposes:
1/ Caching
2/ Logging
3/ Error Handling
4/ Custom Headers
5/ Throttling and Rate Limiting
6/ Compression/Decompression
7/ Authentication and Authorization
8/ 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 :
I am using delegating handler with Refit API so its registration looks like this :
You can register custom HttpClient
like this if you are not using Refit
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 Repository
Whenever you’re ready, there are 2 ways I can help you
Promote yourself to 7000+ subscribers by Sponsoring my Newsletter
Become a Patron and get access to 160+ .NET Questions and Answers
Special Offers
Pragmatic Clean Architecture: Learn how to confidently ship well-architected production-ready apps using clean architecture. [ 10% discount with promo code MUWAS]
Ultimate ASP.NET Core Web API Second Edition - Premium Package [10% discount with promo code 9s6nuez]
Great, very useful, thanks!