C# HttpClient utility class for calling Web API

By | November 22, 2017

Folks writing C# code for consuming resources from external apis or mostly http systems typically use bunch of networking classes. Especially, there are

These classes, however, there is a good dose of confusion around their usage, when to use and their good and bad parts. We’re not going to get into that debate. For those interested to know bit about their history, check this link.  We can safely say not all of them are in vogue right now. HttpClient is considered best of them and treated as successor with all good features.

HttpClient is a high-level API for sending HTTP web requests.  HttpClient has evolved from WebClient and HttpWebRequest

  • HttpClient provides Async methods for making Web API Restful calls.
  • Mocking and testing HttpClient is easy.
  • Single HttpClient can make concurrent requests.
  • HttpClient is available in .Net Framework 4.5 and above

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads.

 

  Avoid Ad hoc code utilizing HttpClient which comes with lot of ceremony and hard to test which may make sense for single usage. However, if you have API layer to address your CRUD needs, it’s better to avoid repetitive code directly references to HttpClient class littered every where in calling code which can spiral out of control in no time. It’s good to have HttpClient abstraction layer as shown below

Following code sample provides a generic abstraction class for HttpClient which can abstract away all the ceremony around initializing HttpClient class, headers, content types and verbs like (GET, PUT,POST, DELETE) inside a helper class with good exception handling, cancellation token support and strongly typed generic version. This layer can turn your usage of HttpClient into a single line of code with out much ceremony when making Restful calls from client code and also aids in testing.