GZipStream in an WebHttpResponse producing no data

Posted by Pierre 303 on Stack Overflow See other posts from Stack Overflow or by Pierre 303
Published on 2010-12-23T14:47:46Z Indexed on 2010/12/23 14:54 UTC
Read the original article Hit count: 283

Filed under:
|
|
|

I want to compress my HTTP Responses for client that supports it.

Here is the code used to send a standard response:

IHttpClientContext context = (IHttpClientContext)sender;
IHttpRequest request = e.Request;

string responseBody = "This is some random text";

IHttpResponse response = request.CreateResponse(context);

using (StreamWriter writer = new StreamWriter(response.Body))
{
    writer.WriteLine(responseBody);
    writer.Flush();
    response.Send();
}

The code above works fine. Now I added gzip support below. When I test it with a browser that supports gzip or a custom method, it returns an empty string. I'm sure I'm missing something simple, but I just can't find it...

IHttpClientContext context = (IHttpClientContext)sender;
IHttpRequest request = e.Request;

string acceptEncoding = request.Headers["Accept-Encoding"];
string responseBody = "This is some random text";

IHttpResponse response = request.CreateResponse(context);

if (acceptEncoding != null && acceptEncoding.Contains("gzip"))
{
    byte[] bytes = ASCIIEncoding.ASCII.GetBytes(responseBody);
    response.AddHeader("Content-Encoding", "gzip");

    using (GZipStream writer = new GZipStream(response.Body, CompressionMode.Compress))
    {
         writer.Write(bytes, 0, bytes.Length);
         writer.Flush();
         response.Send();
    }
 }

 else
 {
     using (StreamWriter writer = new StreamWriter(response.Body))
     {
           writer.WriteLine(responseBody);
           writer.Flush();
           response.Send();
      }
 }

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET