System.Net.ProtocolViolationException:要写入流的字节超出指定的 Content-Length 字节大小

use*_*620 3 c# outputstream httplistener

我基于HttpListener编写Web服务器代码,但经常出现这样的异常

“System.Net.ProtocolViolationException:要写入流的字节超出指定的 Content-Length 字节大小”。

示例代码:

context.Response.Output = System.Text.Encoding.UTF8.GetBytes("xxx");
if (context.Response.Output != null && context.Response.Output.Length > 0)
{
    context.Response.ContentLength64 = context.Response.Output.Length;
    using (var stream = context.Response.OutputStream)
    {
        stream.Write(context.Response.Output, 0, context.Response.Output.Length);
    }
}
Run Code Online (Sandbox Code Playgroud)

并非每次请求都会出现此异常。谁能告诉我怎么解决。谢谢!

hun*_*aro 5

您似乎与下面的问题有同样的问题。您需要检查 HttpMethod 是否是 HEAD 请求;在这种情况下,您无法将字节写入 OutputStream,并且尝试这样做将引发您收到的异常。

Chrome 中的 ProtocolViolationException