2012-05-17 199 views
3

我只是想调整我的方法来传输我的数据,当浏览器接受gzip压缩。 else部分已经有效。我只是想调整if部分。继承人代码:Gzip压缩asp.net c#

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

你为什么不使用Web服务器配置来压缩数据的原因? – Jacob

回答

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

完美。谢啦。 –

0

您应该使用GZipStream类。

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