C# HttpListener 响应 +压缩流
我将 HttpListener 用于我自己的 http 服务器(我不使用 IIS)。我想通过 GZip 压缩来压缩我的 OutputStream:
byte[] refBuffer = Encoding.UTF8.GetBytes(...some data source...);
var varByteStream = new MemoryStream(refBuffer);
System.IO.Compression.GZipStream refGZipStream = new GZipStream(varByteStream, CompressionMode.Compress, false);
refGZipStream.BaseStream.CopyTo(refHttpListenerContext.Response.OutputStream);
refHttpListenerContext.Response.AddHeader("Content-Encoding", "gzip");
但是我在 Chrome 中遇到错误:
ERR_CONTENT_DECODING_FAILED
如果我删除 AddHeader,那么它可以工作,但响应的大小似乎没有被压缩。我做错了什么?
I use HttpListener for my own http server (I do not use IIS). I want to compress my OutputStream by GZip compression:
byte[] refBuffer = Encoding.UTF8.GetBytes(...some data source...);
var varByteStream = new MemoryStream(refBuffer);
System.IO.Compression.GZipStream refGZipStream = new GZipStream(varByteStream, CompressionMode.Compress, false);
refGZipStream.BaseStream.CopyTo(refHttpListenerContext.Response.OutputStream);
refHttpListenerContext.Response.AddHeader("Content-Encoding", "gzip");
But I getting error in Chrome:
ERR_CONTENT_DECODING_FAILED
If I remove AddHeader, then it works, but the size of response is not seems being compressed. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是您的转移方向错误。您想要做的是将 GZipStream 附加到 Response.OutputStream,然后在 MemoryStream 上调用 CopyTo,传入 GZipStream,如下所示:
The problem is that your transfer is going in the wrong direction. What you want to do is attach the GZipStream to the Response.OutputStream and then call CopyTo on the MemoryStream, passing in the GZipStream, like so:
第一个问题(正如 Brent M Spell 提到的)是头的位置错误。第二是你没有正确使用GZipStream。该流需要一个“顶部”流来写入,这意味着一个空流(您用缓冲区填充它)。有了一个空的“顶部”流,那么您所要做的就是在 GZipStream 上写入您的缓冲区。结果,内存流将被压缩内容填充。所以你需要类似的东西:
The first problem (as mentioned by Brent M Spell) is the wrong position of the header. The second is that you don't use properly the GZipStream. This stream requires a "top" stream to write to, meaning an empty stream (you fill it with your buffer). Having an empty "top" stream then all you have to do is to write on GZipStream your buffer. As a result the memory stream will be filled by the compressed content. So you need something like:
希望这可能有所帮助,他们讨论了如何让 GZIP 工作。
C# 中的套接字:如何获取响应流?
Hopeful this might help, they discuss how to get GZIP working.
Sockets in C#: How to get the response stream?