What is the best way to compress a request to asp.net core 2 site using HttpClient?
So I got it to work with simple middleware on the server side and not too much work on the client side. I used CompressedContent.cs from WebAPIContrib, as Rex suggested in the comments of his answer, and made the request as shown below. The whole throw-exception-if-not-OK is because I am using Polly wrapped around my request with a Retry and wait policy.
Client Side:
using (var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/json"))
using (var compressedContent = new CompressedContent(httpContent, "gzip"))
using (HttpResponseMessage response = client.PostAsync("Controller/Action", compressedContent).Result)
{
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
throw new Exception(string.Format("Invalid responsecode for http request response {0}: {1}", response.StatusCode, response.ReasonPhrase));
}
}
Then on the server side I created a simple piece of middleware that wraps the request body stream with the Gzip stream. To use it, you need to add the line app.UseMiddleware<GzipRequestMiddleware>();
before the call to app.UseMvc();
in your Startup.cs
's Configure
method.
public class GzipRequestMiddleware
{
private readonly RequestDelegate next;
private const string ContentEncodingHeader = "Content-Encoding";
private const string ContentEncodingGzip = "gzip";
private const string ContentEncodingDeflate = "deflate";
public GzipRequestMiddleware(RequestDelegate next)
{
this.next = next ?? throw new ArgumentNullException(nameof(next));
}
public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.Keys.Contains(ContentEncodingHeader) && (context.Request.Headers[ContentEncodingHeader] == ContentEncodingGzip || context.Request.Headers[ContentEncodingHeader] == ContentEncodingDeflate))
{
var contentEncoding = context.Request.Headers[ContentEncodingHeader];
var decompressor = contentEncoding == ContentEncodingGzip ? (Stream)new GZipStream(context.Request.Body, CompressionMode.Decompress, true) : (Stream)new DeflateStream(context.Request.Body, CompressionMode.Decompress, true);
context.Request.Body = decompressor;
}
await next(context);
}
}
You may need to enable compression as shown below
var handler = new HttpClientHandler();
if (handler.SupportsAutomaticDecompression)
{
handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
var client = new HttpClient(handler);
MSDN Reference: Using automatic decompression with HttpClient