Logging HttpRequests using DelegatingHandler with a named HttpClient and HttpMessageHandlers in Umbraco

Ever found yourself logging the same things over and over again in your Umbraco application when doing HttpClient requests?

Wouldn't it be nice (if we could wake up) and all of our request where automatically logged for us in one unified way throughout our entire application?

Hello HttpMessageHandlers!

Imagine you're calling some sort of external api, its not unusual (to be in love with anyone) to have your code look something like this:

Now this piece of logging logic might be duplicated and spread around multiple times in your application and it becomes somewhat of a hazzle to maintain once you find yourself wanting to tweak the logging template or behaviour.

The other day one of my coworkers (Thanks Gustav!) demonstrated to our team how this may be avoided by using something called DelegatingHandlers and HttpMessageHandlers in .NET. So obviously I had to bring this to an Umbraco application and try it out, so here goes:

  1. Create a DelegatingHandler and call it something sazzy (in my case LogHttpRequest-DelegatingHandler.cs).
    The big bang theory cat GIF on GIFER - by Zolom

  2. Move the previous logging logic away from the controller and in to this new handler and you get something like this:


  3. In your Startup.cs class you need to register this new DeletagingHandler in the secvice collection.


  4. The last thing you need to do is adding a named HttpClient in your Program.cs file, in the CreateHostBuilder, together with an HttpMessageHandler pointing at your new DelegatingHandler:

    (FYI: The NamedHttpClient.LoggingHttpClient is nothing magical, it's just a constant class I store the name of my named HttpClient in case I want to rename it one day. You can type any string in there.)

So now that we have our new HttpClient we can go ahead and use this in our previous code example. By referencing our named HttpClient and call the external request we can from this point forward ignore any form of logging since this will be taken care of automatically for us. So this is what we end up with:

Nice and slim, right? And even though we aren't doing any logging in the controller request, if we dig in to the Umbraco logs we find this logging being made every time we make a new request using this HttpClient anywhere in our application:

That's it, that's all!
Sorry for all the music references, I couldn't help myself. ;)

Cheers friends! ❤️