HttpListenerException“参数错误”
本文关键字:参数错误 错误 参数 HttpListenerException | 更新日期: 2023-09-27 18:14:14
我试图服务器一个HttpListenerResponse与一些Json数据,但不断得到一个异常时写入到HttpListenerResponse输出流。
我首先设置响应头,然后设置contentlength,最后将数据写入输出流。
response.StatusCode = endpointResponse.Status;
response.ContentType = endpointResponse.ContentType;
response.ContentLength64 = endpointResponse.Payload.Length;
//response.OutputStream.Write(endpointResponse.Payload, 0, endpointResponse.Payload.Length); // Throws same exception
using (var output = response.OutputStream)
{
using (var writer = new BinaryWriter(output))
{
writer.Write(endpointResponse.Payload); // Throws exception here.
writer.Flush();
}
}
response.OutputStream.Close();
这会导致writer.Write(endpointResponse. payload)或response.OutputStream.Write(endpointResponse. payload)中出现异常。有效载荷,0,endpointResponse.Payload.Length)
抛出相同的HttpListenerExceptoin,消息为{"参数不正确"}和ErrorCode 87.
at System.Net.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.BinaryWriter.Write(Byte[] buffer)
at FarmLink.Server.Http.HttpHandler.BuildResponse(HttpListenerResponse response, EndpointResponse endpointResponse) in c:'wc'FarmLink'src'FarmLink.Server.Http'HttpHandler.cs:line 82
at FarmLink.Server.Http.HttpHandler.<ContextCallback>d__0.MoveNext() in c:'wc'FarmLink'src'FarmLink.Server.Http'HttpHandler.cs:line 56
任何想法?
更改代码顺序,似乎可以工作。所以不需要在OutputStream的数据前写入头文件到
response.ContentLength64 = endpointResponse.Payload.Length;
response.OutputStream.Write(endpointResponse.Payload, 0, endpointResponse.Payload.Length);
response.OutputStream.Close();
foreach (var endpointParameter in endpointResponse.Headers)
{
response.AddHeader(endpointParameter.Key, endpointParameter.Value);
}
response.StatusCode = endpointResponse.Status;
response.ContentType = endpointResponse.ContentType;
似乎奏效了。
知道为什么吗?