Skip to content

HTTP Compression - Improve/fix support for user-specified Accept-Encoding encodings #46948

@EatonZ

Description

@EatonZ

Background

To specify Accept-Encoding encodings for HTTP requests, you set AutomaticDecompression in a HttpMessageHandler-based class (such as SocketsHttpHandler). If you wish to change the order the encodings, or add quality weightings, the workaround seems to be to add the encodings manually before the request is sent:

if (handler.AutomaticDecompression.HasFlag(DecompressionMethods.Brotli)) request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("br", 1.0));
if (handler.AutomaticDecompression.HasFlag(DecompressionMethods.GZip)) request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("gzip", 0.9));
if (handler.AutomaticDecompression.HasFlag(DecompressionMethods.Deflate)) request.Headers.AcceptEncoding.Add(new StringWithQualityHeaderValue("deflate", 0.8));

The Problem

After reviewing the .NET source, I found that DecompressionHandler does take into account the existence of user-added encodings before it adds any (code starts here).

Due to the way these checks are set up, with quality weightings added to the encodings, the resulting Contains return false and duplicate encodings are unnecessarily added.

This is what the header ends up looking like:
Accept-Encoding: br; q=1.0, gzip; q=0.9, deflate; q=0.8, gzip, deflate, br

Proposed Fix/Improvement

Replace Contains with a better check. For each encoding already in AcceptEncoding, you should check it with StartsWith.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions