当我对我的 HTTP 响应应用 gzip 或 deflate 压缩时,我似乎丢失了 JSON 结构中的最后一个括号。例如:
没有压缩的结果:
{"alist":{"P_1":0,"P_2":0,"P_3":0}}
浏览器收到的压缩结果:
{"alist":{"P_1":0,"P_2":0,"P_3":0}
在没有压缩的情况下编写响应时,我正在执行以下操作:
byte[] buffer = Encoding.UTF8.GetBytes(responseContent);
context.Response.ContentLength64 = buffer.Length;
context.Response.ContentType = ContentTypeJson;
Stream outputStream = context.Response.OutputStream;
outputStream.Write(buffer, 0, buffer.Length);
outputStream.Close();
或者,当调用者提供 Accept-Encoding 请求标头时,我尝试使用压缩编写响应,如下所示;
byte[] buffer = Encoding.UTF8.GetBytes(responseContent);
byte[] compressedBuffer;
using (var memoryStream = new MemoryStream())
{
using (Stream compressionStream = new DeflateStream(memoryStream, CompressionMode.Compress, false))
{
compressionStream.Write(buffer, 0, buffer.Length);
compressedBuffer = memoryStream.ToArray();
compressionStream.Close();
}
memoryStream.Close();
}
context.Response.ContentLength64 = compressedBuffer.Length;
context.Response.ContentType = ContentTypeJson;
Stream outputStream = context.Response.OutputStream;
outputStream.Write(compressedBuffer, 0, compressedBuffer.Length);
outputStream.Close();
如果有帮助,我正在使用 System.Net.HttpListener,这就是我必须自己做的原因。有谁知道为什么会发生这种截断?