C # HttpListener Response + GZipStream

I use HttpListener for my own HTTP server (I do not use IIS). I want to compress my OutputStream using GZip compression:

byte[] refBuffer = Encoding.UTF8.GetBytes(...some data source...);

var varByteStream = new MemoryStream(refBuffer);

System.IO.Compression.GZipStream refGZipStream = new GZipStream(varByteStream, CompressionMode.Compress, false);

refGZipStream.BaseStream.CopyTo(refHttpListenerContext.Response.OutputStream);

refHttpListenerContext.Response.AddHeader("Content-Encoding", "gzip");

But I get an error in Chrome:

ERR_CONTENT_DECODING_FAILED

If I remove AddHeader, then it will work, but the size of the response does not seem compressed. What am I doing wrong?

+5
source share
3 answers

The problem is that your translation is going in the wrong direction. What you want to do is connect GZipStream to Response.OutputStream, and then call CopyTo on a MemoryStream, passing GZipStream, for example:

refHttpListenerContext.Response.AddHeader("Content-Encoding", "gzip"); 

byte[] refBuffer = Encoding.UTF8.GetBytes(...some data source...); 

var varByteStream = new MemoryStream(refBuffer); 

System.IO.Compression.GZipStream refGZipStream = new GZipStream(refHttpListenerContext.Response.OutputStream, CompressionMode.Compress, false); 

varByteStream.CopyTo(refGZipStream); 
refGZipStream.Flush();
+9
source

( Brent M Spell) - . -, GZipStream . "" , ( ). "" , , , GZipStream . . - :

byte[] buffer = ....;

using (var ms = new MemoryStream())
{
    using (var zip = new GZipStream(ms, CompressionMode.Compress, true))
    zip.Write(buffer, 0, buffer.Length);
    buffer = ms.ToArray();
}

response.AddHeader("Content-Encoding", "gzip");
response.ContentLength64 = buffer.Length;

response.OutputStream.Write(buffer, 0, buffer.Length);
+4

Hope this helps, they discuss how to make gzip work.

Sockets in C #: how to get a response stream?

0
source

All Articles