Writing cleaner Typed HttpClient using a custom DelegatingHandler
Introduction
I write a lot of HttpClient, including typed client. Since I discovered Refit I use only that one, I write so less lines of code! But I thought about you! Some of you do not necessarily use Refit so I’ll give you some tips for writing typed HttpClient with maximum reusability using HttpClient Message Handlers and more specifically DelegatingHandlers.
Writing a typed HttpClient that forwards a JWT and logs errors
Here is the typed HttpClient to clean:
There many things here to clean because they might be redundant in every clients you’ll write in the same application:
- Read Access Token from HttpContext
- Manage Access Token when it’s empty
- Attach Access Token to the HttpClient to delegate it
- Read CorrelationId from HttpContext
- Attach CorrelationId to the HttpClient to delegate it
- Verify the success of the Http query with EnsureSuccessStatusCode()
Writing a custom DelegatingHandler that handles redundants code
Here is the DelegatingHandler:
As you can see, now it encapsulates the redundant logic used for every HttpClient consumed in the same application.
Now the the cleaned HttpClient looks like this:
Much better isn’t it? 🙂
Finally let’s attach the DelegatingHandler to the HttpClient in Startup.cs:
Using Refit
If you are using Refit you can definitely reuse that DelegatingHandler !
Example: