ninject and gzip response conflict

39 Views Asked by At

I am using this compress attribute to compress my response from web API. After adding ninject to my project, the compress attribute doesn't work correctly, and it produces some unrecognized character like this:

   h=d  ݛMo 6    ΂ߢxl C)
xoE W  cW6  }IQ    fb B `I "  ;3 |+N   ) ߊ   ևۦ0dE      i  >    ~jv   闯    Ԭ   R{l  

How can I resolve it?

using  System.IO.Compression;

public class CompressAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var encodingsAccepted = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
        if (string.IsNullOrEmpty(encodingsAccepted)) return;

        encodingsAccepted = encodingsAccepted.ToLowerInvariant();
        var response = filterContext.HttpContext.Response;

        if (encodingsAccepted.Contains("deflate"))
        {
            response.AppendHeader("Content-encoding", "deflate");
            response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
        }
        else if (encodingsAccepted.Contains("gzip"))
        {
            response.AppendHeader("Content-encoding", "gzip");
            response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
        }
    }
}
```
1

There are 1 best solutions below

1
Mark Adler On

It is entirely expected and correct for compression to produce unprintable characters. All 256 possible byte values are used for maximum compression.

Your code is incorrect in that the HTML encoding "deflate" actually means a zlib stream, not a raw deflate stream. (Unfortunate choice of a word there.) So you need to use zlibStream in that case, not deflateStream.