Gzip Asp.net C # Compression

I just want to configure my method to transfer my data when the browser accepts gzip. Part is elsealready working. I just want to adjust the part if. Here is 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();
    }
}
+3
source share
3 answers

It looks like you want to add 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();
    }

}
+8
source

You must use the GZipStream class .

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

All Articles