Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 压缩HTTP响应时JSON被截断_C#_Json_Compression_Deflate_Httplistener - Fatal编程技术网

C# 压缩HTTP响应时JSON被截断

C# 压缩HTTP响应时JSON被截断,c#,json,compression,deflate,httplistener,C#,Json,Compression,Deflate,Httplistener,当我对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.Cont

当我对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();
或者,当调用方提供一个接受编码请求头时,我尝试用压缩编写响应,如下所示:

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,这就是为什么我必须自己做这件事。有人知道为什么会发生这种截断吗?

DeflateStream
不会在写入输出流后立即将所有内容写入其输出流,但您可以确定在关闭它后它已经这样做了。因此,以下措施将起作用:

compressionStream.Write(buffer, 0, buffer.Length);

compressionStream.Close();

compressedBuffer = memoryStream.ToArray();

在从基础memoryStream读取数组之前,请尝试刷新压缩流。顺序就是一切。。。你是对的,这似乎解决了问题。非常感谢。