2012-05-17 2 views
3

Я просто хочу настроить свой метод для передачи моих данных, сжатых, когда браузер принимает gzip. Часть else уже работает. Я просто хочу отрегулировать часть if. Heres код:Gzip compression 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

Любая причина, по которой вы не используете конфигурацию веб-сервера для сжатия данных вместо этого? – 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); 
}