How to Automatically unzip compressed response with .Net Core HttpClient

Http response compression is a great way to improve performance of your web applications. Performance improvement is not just limited to web pages. You can use same response compression for web api as well to improve performance of client requests. .Net Core makes it easy to configure response compression. I will just briefly mention how you achieve this for your .Net Core web application.

// Set up during service conifguration

// Set up during request pipe line congiguration

A lot of time you have to implement services in your application that require you to make Http request to get some data that you need to consume. In my earlier post Ethereum Price API I showed how I was getting data from to build my Ethereum Price Widget.

var httpClient = _httpClientFactory.CreateClient(AmgrHttpDefaults.DefaultHttpClientForCompressedResponse);
var priceFeed = await httpClient.GetStringAsync(string.IsNullOrEmpty(_feedSettings.PriceFeedUrl) ? PriceIndexFeedUrl: _feedSettings.PriceFeedUrl);
var priceIndexFeed = JsonConvert.DeserializeObject<IList<EthereumPriceFeedModel.PriceIndexValue>>(priceFeed);

I used IHttpClientFactory to create my named HttpClient instance. Notice that I have used a name for my HttpClient that tells me that this HttpClient will handle compressed response. Just because I named it that way does not mean that it will automatically will uncompress the response for me. Let's see how this works.

Add HttpClient

During services configuration step, you will add HttpClient to IServiceCollection.


Notice that I have called WithAutomaticDecompression method to set up client factory to handle compressed response correctly. There is no such method in .Net core. It is an extension method that I implemented in my code to set up the required properties.

public static void WithAutomaticDecompression(this IHttpClientBuilder httpClientBuilder)
            httpClientBuilder.ConfigurePrimaryHttpMessageHandler(() =>
                var handler = new HttpClientHandler
                    AutomaticDecompression = DecompressionMethods.All
                return handler;

There are multiple options available for handling different formats of compressed response. In .Net Core documentation you can look for DecompressionMethods enum. You will see following values.

  • All - Use all compression-decompression algorithms.
  • Brotli - Use the Brotli compression-decompression algorithm.
  • Deflate - Use the deflate compression-decompression algorithm.
  • GZip - Use the gZip compression-decompression algorithm.
  • None - Do not use compression.

If you are particular about type of compression-decompression algorithm, then you can pick that particular value.

This is all that you will need to set up to allow automatic handling of compression and decompression of HTTP response returned by HttpClient requests.




7.9 °C / 46.1 °F

weather conditions Rain

Monthly Posts

Blog Tags