3

I just want to adjust my method to transfer my data compressed when browser accepts gzip. The else part already works. I just want to adjust the if part. Heres the code:

private void writeBytes()
{
    var response = this.context.Response;

    if (canGzip)
    {
        response.AppendHeader("Content-Encoding", "gzip");
        //COMPRESS WITH GZipStream
    }
    else
    {
        response.AppendHeader("Content-Length", this.responseBytes.Length.ToString());
        response.ContentType = this.isScript ? "text/javascript" : "text/css";
        response.AppendHeader("Content-Encoding", "utf-8");
        response.ContentEncoding = Encoding.Unicode;
        response.OutputStream.Write(this.responseBytes, 0, this.responseBytes.Length);
        response.Flush();
    }
}
Jeremy
  • 8,902
  • 2
  • 36
  • 44
Rodrigo Manguinho
  • 1,411
  • 3
  • 21
  • 27

2 Answers2

8

Looks like you want to add the Response.Filter, see below.

private void writeBytes()
{
    var response = this.context.Response;
    bool canGzip = true;

    if (canGzip)
    {
        Response.Filter = new System.IO.Compression.GZipStream(Response.Filter, System.IO.Compression.CompressionMode.Compress);
        Response.AppendHeader("Content-Encoding", "gzip");
    }
    else
    {
        response.AppendHeader("Content-Encoding", "utf-8");
    }

    response.AppendHeader("Content-Length", this.responseBytes.Length.ToString());
    response.ContentType = this.isScript ? "text/javascript" : "text/css";
    response.ContentEncoding = Encoding.Unicode;
    response.OutputStream.Write(this.responseBytes, 0, this.responseBytes.Length);
    response.Flush();
    }

}
Zachary
  • 6,522
  • 22
  • 34
0

You should use the GZipStream class.

using (var gzipStream = new GZipStream(streamYouWantToCompress, CompressionMode.Compress))
{
    gzipStream.CopyTo(response.OutputStream);
}
Jacob
  • 77,566
  • 24
  • 149
  • 228