8.12Response Content Decompression (Supporting gzip, deflate, brotli and zstd) and Content Encoding Issues
In modern mainstream web frameworks, most have built-in support for compressing server response content, with the most commonly used compression methods being gzip, deflate, brotli and zstd. When making an HTTP request, if the response content returned by the server has compression enabled, by default the framework automatically decompresses this content (for the gzip, deflate, brotli and zstd formats).
If you need to enable custom decompression, you can achieve this by configuring the client behavior. The specific method is as follows:
Configuring automatic decompression
// Configure the default clientservices.AddHttpClient(string.Empty) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AutomaticDecompression = DecompressionMethods.All, // Enable automatic decompression for gzip, deflate, brotli and zstd // AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate // Enable automatic decompression for gzip and deflate only });With the configuration above, if AutomaticDecompression is set to DecompressionMethods.All, the framework automatically handles response content compressed with the gzip, deflate, brotli and zstd formats; if it is set only to DecompressionMethods.GZip | DecompressionMethods.Deflate, then only content compressed with gzip and deflate is automatically decompressed.
Note that the framework only attempts automatic decompression when the Content-Encoding response header contains one of the compression methods above. Therefore, in a configuration that does not include brotli, the corresponding response content will not be automatically decompressed.
Manually handling decompression (such as when automatic decompression fails or when processing non-standard encodings)
When you need to handle decompression manually, follow these steps:
- Disable automatic decompression
// Configure the default client and disable all automatic decompressionservices.AddHttpClient(string.Empty) .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AutomaticDecompression = DecompressionMethods.None // Disable automatic decompression });- Check the
Content-Encodingresponse header
var response = await httpRemoteService.GetAsync("https://furion.com");if (response.Content.Headers.ContentEncoding.Contains("gzip")){ // gzip encoding detected, manual decompression can be performed}- Perform manual decompression (using
gzipas an example)
using var responseStream = await response.Content.ReadAsStreamAsync();using var gzipStream = new GZipStream(responseStream, CompressionMode.Decompress);using var reader = new StreamReader(gzipStream);var content = await reader.ReadToEndAsync();Console.WriteLine(content);