我想压缩支持它的客户端的http响应。我用的是C# Webserver
以下是用于发送标准响应的代码:

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

上面的代码工作正常。现在我在下面添加了gzip支持。当我用支持gzip或自定义方法的浏览器测试它时,它返回一个空字符串。我肯定我漏掉了一些简单的东西,但我就是找不到…
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();
      }
 }

最佳答案

皮埃尔,皮埃尔,皮埃尔……
您的代码无法按预期工作。
GZipStream必须在从基础流读取之前关闭。因为GZipStreamGZipStream.Dispose中写入必需的gzip页脚。
以下代码将起作用:

using (MemoryStream stream = new MemoryStream())
{
     using (GZipStream gZipStream = new GZipStream(stream, CompressionMode.Compress))
     gZipStream.Write(bytes, 0, bytes.Length);

     byte[] compressed = stream.ToArray();
     response.Body.Write(compressed, 0, compressed.Length);

     response.Send();
}

10-04 22:41