使用Google Chrome和HTTPListener获取ProtocolViolationException

pat*_*ice 5 .net c# browser httplistener

我开发了一个管理工具,我使用一个简单的HTTPListener来返回HTML页面.一切都适用于IEFF但我在使用谷歌浏览器时遇到了ProtocolViolationException.

这是产生错误的简化代码(从listener.BeginGetContext引发):

byte[] buffer = System.Text.Encoding.UTF8.GetBytes("<html><body>response sent!</body></html>");
context.Response.ContentLength64 = buffer.Length;
context.Response.OutputStream.Write(buffer, 0, buffer.Length); //<-- crashes here
context.Response.OutputStream.Close();
context.Response.Close();
Run Code Online (Sandbox Code Playgroud)

例外

要写入流的字节数超过指定的Content-Length字节大小.

被抛出线

context.Response.OutputStream.Write(buffer,0,buffer.Length);

Chrome做或不做什么来产生此错误?

谢谢

use*_*188 5

我知道这有点太晚了,但我刚刚遇到这个问题(不是Chrome)并且发现了这个问题.当您尝试向OutputStream写入内容以响应HEAD请求时,这个看似防弹的代码会失败.然后将ContentLength64设置为0,并且由于某种原因,当您尝试更改它时没有抛出异常,新值将被静默忽略.

  • 对于记录,您必须至少在收到HEAD请求时在响应流上调用close,否则您将保持卡住状态. (2认同)