Search code examples
c#encodinggziphttplistenergzipstream

C# HttpListener Response + GZipStream


I use HttpListener for my own http server (I do not use IIS). I want to compress my OutputStream by 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 getting error in Chrome:

ERR_CONTENT_DECODING_FAILED

If I remove AddHeader, then it works, but the size of response is not seems being compressed. What am I doing wrong?


Solution

  • The problem is that your transfer is going in the wrong direction. What you want to do is attach the GZipStream to the Response.OutputStream and then call CopyTo on the MemoryStream, passing in the GZipStream, like so:

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