ASP.NET C#中的Gzip压缩

3

我只想调整我的方法,在浏览器接受gzip时传输压缩的数据。已经有了else部分的工作,我只想调整if部分。以下是代码:

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

你为什么不使用Web服务器配置来压缩数据呢? - Jacob
2个回答

8

看起来您想添加Response.Filter,如下所示。

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

}

0
你应该使用 GZipStream 类。
using (var gzipStream = new GZipStream(streamYouWantToCompress, CompressionMode.Compress))
{
    gzipStream.CopyTo(response.OutputStream);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接