title: How to determine whether content returned by .NET HttpClient is Gzipped?
body: <p>I have a requirement to download some content from a remote URL and then also determine whether the content was compressed (Gzip or Deflate).</p>
  
  <p>My issue is that when you allow the <a href="https://msdn.microsoft.com/en-us/library/system.net.http.httpclient" rel="noreferrer">HttpClient</a> to perform <a href="https://msdn.microsoft.com/en-us/library/system.net.http.httpclienthandler.automaticdecompression.aspx" rel="noreferrer">automatic decompression</a> then it doesn't return any value in the <code>response.Content.Headers.ContentEncoding</code> property. If you <em>don't</em> enable automatic decompression then it does return the correct value for <code>ContentEncoding</code> but then you are left with a Gzipped document that hasn't been decompressed, which is not useful.</p>
  
  <p>Take the following code:</p>
  
  <pre><code>var handler = new HttpClientHandler()
  {
      AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
  };
  
  using (var client = new HttpClient(handler))
  {
      client.DefaultRequestHeaders.Add("accept-encoding", "gzip, deflate");
      client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)");
  
      using (var message = new HttpRequestMessage(HttpMethod.Get, new Uri("https://www.twitter.com")))
      {
          using (var response = await client.SendAsync(message))
          {
              if (response.IsSuccessStatusCode)
              {
                  string encoding = String.Join(",", response.Content.Headers.ContentEncoding);
  
                  string content = await response.Content.ReadAsStringAsync();
              }
          }
      }
  }
  </code></pre>
  
  <p>When the <code>HttpClientHandler</code> is set to use <code>AutomaticDecompression</code> then the value in content is successfully requested as GZip and then decompressed correctly. But the <code>ContentEncoding</code> value in the response headers collection is empty.</p>
  
  <p>If I remove the line:</p>
  
  <pre><code>AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
  </code></pre>
  
  <p>then I do get the correct <code>ContentEncoding</code> value ("gzip") returned, but then the document is returned in it's raw compressed format, which is no good.</p>
  
  <p>So is there any way to get content that may sometimes (but not always) be GZipped and automatically decompress it when it is, but then know afterward whether it was originally sent as Gzip?</p>