Skip to content

Latest commit

 

History

History
119 lines (78 loc) · 2.98 KB

DOCUMENTATION.md

File metadata and controls

119 lines (78 loc) · 2.98 KB

HTTP request compression - Overview

Introduction

The library includes built-in compression providers for Brotli, DEFLATE, and GZIP formats. With the default options, any HTTP request content of the "application/json" media type will be compressed with Brotli format using the fastest level of compression. Use OPTIONS request method with an HTTP compression context to discover an available compression encoding supported by a server.

Note

The built-in DEFLATE compression provider uses ZLIB compression format.

How to Use

How to add the compression handler to a named HTTP client with default settings:

services.AddHttpClient("my-client")
        .AddCompressionHandler();

How to add the compression handler to a named HTTP client with specific settings:

services.AddHttpClient("my-client")
        .AddCompressionHandler(options =>
        {
            options.MediaTypes.Add("application/json-seq");
            options.CompressionEncoding = "deflate";
            options.CompressionLevel = CompressionLevel.Optimal;
        });

How to add the compression handler to a named HTTP client with specific shared settings:

services.Configure<HttpCompressionOptions>(options =>
        {
            options.MediaTypes.Add("application/json-seq");
            options.CompressionEncoding = "deflate";
            options.CompressionLevel = CompressionLevel.Optimal;
        });

services.AddHttpClient("my-client")
        .AddCompressionHandler();

How to discover and apply a compression encoding supported by a server as per RFC 7694:

var context = new HttpCompressionContext();
var request1 = new HttpRequestMessage(HttpMethod.Options, "/api/items");

request1.Options.Set(HttpCompressionOptionKeys.HttpCompressionContext, context);

await httpClient.SendAsync(request1);

var request2 = new HttpRequestMessage(HttpMethod.Post, "/api/items");

request2.Content = JsonContent.Create(item);
request1.Options.Set(HttpCompressionOptionKeys.HttpCompressionContext, context);

await httpClient.SendAsync(request2);

The compression encoding discovery support can be added for a server using the build-in middleware:

app.Use((context, next) =>
{
    if (string.Equals(context.Request.Method, HttpMethods.Options))
    {
        var options = app.Services.GetService<IOptions<RequestDecompressionOptions>>();

        if (options is not null)
        {
            var encodingNames = options.Value.DecompressionProviders.Keys;

            context.Response.Headers.AcceptEncoding = string.Join(',', encodingNames);
        }
    }

    return next(context);
});

app.Run();

References