我试图使用一些Json数据来服务HttpListenerResponse,但在写入HttpListenerResponse输出流时不断收到异常。
首先设置响应头,然后设置contentLenght,最后将数据写入输出流。
# If requested resource exists as a file or directory go to it
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*) - [L]
# Else rewrite requests for non-existent resources to /index.php
RewriteRule (.*) /? [L]
这导致 writer.Write(endpointResponse.Payload)或 response.OutputStream.Write(endpointResponse.Payload,0,endpointResponse.Payload.Length)中的异常
两者都抛出相同的HttpListenerExceptoin,消息为{"参数不正确"}和ErrorCode 87。
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();
有什么想法吗?
答案 0 :(得分:1)
更改代码的顺序,似乎有效。因此,不要将数据前的标头写入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;
似乎可以做到这一点。
知道为什么吗?