System.Net.HttpClient Best Practices

What is HttpClient

HttpClient is a Portable Class Library from Microsoft for HTTP communications. It is completely asynchronous and has excellent features for extensibility. It is absolutely great, especially when communicating with REST based services. It's miles better than the old HttpWebRequest and is much easier to work with in my experience.

Examples to get you started


var client = new HttpClient();  
HttpResponseMessage response = await client.GetAsync("");  
string content = await response.Content.ReadAsStringAsync();  

As you can see it is dead simple to use, but that doesn't mean that it isn't powerful. Let's look at more examples.

Fetching using GZip compression

var handler = new HttpClientHandler();  
if (handler.SupportsAutomaticDecompression)  
    handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

var client = new HttpClient(handler);  
HttpResponseMessage response = await client.GetAsync("");  
string content = await response.Content.ReadAsStringAsync();  

Here we set up the HttpClient with a handler which is built into the library to enable GZip and Deflate decompressions. It automatically adds the Accept-Encoding: gzip, deflate header and takes care of the content decompression for you.

Reusing headers between requests

HttpClient also has the ability to reuse commonly used header between requests. This is especially handy for things like Authorization and Accept headers when talking to RESTful APIs. For this purpose the HttpClient hsa a property called DefaultRequestHeaders.

You can for example set the Authorization header like this:

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", "my_awesome_access_token");  

This means that the Authorization header will be used for all subsequent GetAsync, PutAsync, PostAsync or DeleteAsync methods etc.

Do not create a new HttpClient for every HTTP request in your app

Although the HttpClient implements IDisposable it is meant to be reused between requests. Therefore you should try to reuse the instance of it as much as possible. This yields better performance by reusing TCP ports and reduces unnecessary allocations for things like the default request headers. It also results in neater code by only intializing things like GZip compression and the default request headers early.

If you need to send different request headers between requests use SendAsync with a custom HttpRequestMessage.

The GetAsync, PostAsync, PutAsync etc. methods use the Authorization, CacheControl etc. Headers as defined in the DefaultRequestHeader property. If you need to send requests without these headers or need to override them, create a custom HttpRequestMessage and send it using the SendAsync method. It give you more control over the exact request that you are going to send.

I highly reccommend you look at the HttpClient library. It is greatly improved over the old HttpWebRequest method of getting HTTP requests done and is much more customizable. You can find it easily on NuGet by searching for HttpClient.

Hope this helps.

Stefán Jökull Sigurðarson

Read more posts by this author.