简体   繁体   中英

HttpListenerException “The parameter is incorrect”

I'm trying to server a HttpListenerResponse with some Json data, but keep getting an exception when writing to the HttpListenerResponse outputstream.

I start by setting the response headers, then setting contentLenght and last writing the data to the output stream.

      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();

This results in a exception in writer.Write(endpointResponse.Payload) or in response.OutputStream.Write(endpointResponse.Payload, 0, endpointResponse.Payload.Length)

Both throws the same HttpListenerExceptoin with message {"The parameter is incorrect"} and 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

Any ideas?

Change the order of code, seems to work. So instead of writing headers before data to the OutputStream to

    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;

Seems to do the trick.

Any idea why?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM