GZipStream in an WebHttpResponse producing no data
- by Pierre 303
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();
}
}