New HTTP request compression options in .NET 11 Preview 7: GZip, Brotli and Zstandard

Posted: (EET/GMT+2)

 

Microsoft just recently released the latest Preview 7 for .NET 11 and C# 15, and one of the things (among many!) it contains is improved support for HTTP request body compression.

The new classes GZipCompressedContent, BrotliCompressedContent, and ZstandardCompressedContent in the System.Net.Http namespace allow you to use these compression methods when you use HttpClient to send for instance a POST request. Of course, the destination web server also needs to support the same compression for this to work.

Here's a small example:

using System.IO.Compression;
using System.Net.Http;

using HttpClient client = new();
StringContent payload = new("""{"greeting":"hello"}""");

using HttpRequestMessage request = new(HttpMethod.Post, "https://api.example.com/some-endpoint")
{
    Content = new ZstandardCompressedContent(payload, CompressionLevel.Optimal),
};

using HttpResponseMessage response = await client.SendAsync(request);

Sounds very good, especially if you know you're sending content that compresses well, such as JSON.

PS. On the C# front, be sure to check out Preview 7's labeled break and continue. Nice!