Rodrigo Manguinho
Rodrigo Manguinho

Reputation: 1411

Gzip compression asp.net c#

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();
    }
}

Upvotes: 3

Views: 8240

Answers (2)

Zachary
Zachary

Reputation: 6532

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();
    }

}

Upvotes: 8

Jacob
Jacob

Reputation: 78850

You should use the GZipStream class.

using (var gzipStream = new GZipStream(streamYouWantToCompress, CompressionMode.Compress))
{
    gzipStream.CopyTo(response.OutputStream);
}

Upvotes: 0

Related Questions