0

I have Controller1/Action1, which currently don't care about Accept-Encoding in request and return application/json response always.

Now in same application, we are adding Controller2/Action2, which will return huge json (~5mb) and want to use compression and decided to go with gzip. Our new client_2 of Controller2/Action2 are ready to consume it as gzip.

Though Controller1/Action1 still has to return Content-Encoding as application/json and NOT gzip, as I don't think all client_1s of Controller1/Action1 passes Accept-Encoding header.

So how can I achieve 2 different Content-Encoding on 2 different Actions.

Adding below compression in aspnet pipeline results gzip for all Actions and will not return JSON for Controller1/Action1 which I want always, as I don't think all client_1s has capability to consume gzip

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddResponseCompression(options => { options.EnableForHttps = true; });
            services.Configure<GzipCompressionProviderOptions>(options =>
            {
                options.Level = CompressionLevel.Optimal;
            });
        }

Adding only below attribute on Action seems not having any effect either, I am not getting back any response

[Produces("application/gzip")]
PKV
  • 773
  • 1
  • 7
  • 17

1 Answers1

0

If you compress using GZip, the Action Controller2/Action2 always return data in binary format. So you have to change the "Content-Encoding" in the response Header to binary. For Example, In the response header, try giving the following

Content-Encoding: gzip
Vary: Accept Encoding

In the request header, give the following,

Accept-Encoding: br, compress, gzip 

There is another way, you convert the compressed binary to string using the below code, which will be accepted by the client which accepts JSON.

using (var stream = new MemoryStream())
        {
            using (var zip = new GZipStream(stream, CompressionMode.Compress, true))
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(zip, list);
            }
            var byteArray = stream.ToArray();
            StringBuilder sb = new StringBuilder();
            foreach (byte item in byteArray)
            {
                sb.Append((char)item);
            }
            return sb.ToString();
        }