In a previous post, “.NET 11 Preview - Using Zstandard Decompression With A HttpClient”, we looked at how to configure a HttpClient to transparently decompress traffic compressed using the Zstandard algorithm.

In this post, we will look at the opposite: how to compress outbound traffic with Zstandard.

Suppose we had this type:

public class Spy
{
  public required string Firstname { get; set; }
  public required string Surname { get; set; }
  public required string Agency { get; set; }
  public required DateOnly DateOfBirth { get; set; }
  public required DateOnly HireDate { get; set; }
}

And this instance:

var jamesBond = new Spy
{
  Firstname = "James",
  Surname = "Bond",
  Agency = "MI-6",
  DateOfBirth = new DateOnly(1950, 1, 1),
  HireDate = new DateOnly(1975, 1, 1,)
};

Suppose we needed to send this to an API.

We would typically do it like this:

var client = new HttpClient();
await client.PostAsJsonAsync("https://reqbin.com/echo/post/json", jamesBond);

Here I am using the API testing site https://reqbin.com/.

To compress this, we need to do some additional work.

// Create the payload
var payload = JsonContent.Create(jamesBond);
// Create a HttpRequest
using var request = new HttpRequestMessage(HttpMethod.Post, API_URL);
// Compress the content
request.Content = new ZstandardCompressedContent(payload, CompressionLevel.SmallestSize);
//Post
await client.SendAsync(request);

Here we are doing the following:

  1. Creating a JsonContent object from our Spy type
  2. Creating a POST HttpRequestMessage
  3. Compressing the content
  4. Sending the HttpRequestMessage

IMPORTANT: To do this, the web server should be able to decompress Zstandard-compressed traffic.

TLDR

.NET 11 allows you to use Zstandard to compress traffic to a destination server from a HttpClient.

The code is in my GitHub.

Happy hacking!