2

I'm writing a .Net Web Api (2) that have this one POST method. This method is currently deserializing it's only parameter by using the standard JSON formatter. We are also writing the Client that will consume this Api a C# Client using System.Net.Http.HttpClient to communicate.

There is the potential to be moving a large volume of data. This made us look into reducing the footprint of the request.

After searching this site, I came across some alternatives using gzip compression. I already have a working proof of concept:

  • Client side something down the lines of this
  • Server side something down the lines of this

So, my question...

Do I really need to write all this custom code for this? Is there a built in way to accomplish lowering the footprint of the request?

Some articles that came across mention about enabling gzip (or deflate) in IIS (see Enable IIS7 gzip). This was not working for me (I enabled it, I'm still doing the compression on the Client side, removed the DelegatingHandler from the Server...but nothing, I end up with a null parameter in the controller method)

Community
  • 1
  • 1
qazcde
  • 526
  • 4
  • 19
  • 1
    Did you find a solution for this problem ?? – Jerome2606 Sep 15 '17 at 07:31
  • Nothing out of the box. Following the links I added in my post I ended up implementing a DelegatingHandler that decompresses the requests if a content encoding "gzip" header is present. (overwrites SendAsync). – qazcde Sep 18 '17 at 14:31

1 Answers1

1

I ended up implementing a DelegatingHandler to look for a header with ContentEncoding "gzip" and decompress accordingly.

using System;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

namespace WebApi.MessageHandlers
{
    /// <summary>
    /// GZip message handler. 
    /// </summary>
    public class GZipMessageHandler : DelegatingHandler
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (IsRequestCompressed(request))
            {
                request.Content = Descompress(request.Content);
            }
            return base.SendAsync(request, cancellationToken);
        }

        private bool IsRequestCompressed(HttpRequestMessage request)
        {
            return request.Content.Headers.ContentEncoding.Contains("gzip", StringComparer.OrdinalIgnoreCase);
        }

        private HttpContent Descompress(HttpContent content)
        {
            // Handle compression...
            throw new NotImplementedException();
        }
    }
}
qazcde
  • 526
  • 4
  • 19