Pregunta

Estoy intentando escribir un mensaje un archivo adjunto a CouchDB utilizando el HttpWebRequest. Sin embargo, cuando intento "respuesta = (HttpWebResponse) HttpWebRequest.GetResponse ();" Recibo una WebException con el mensaje "La conexión subyacente se cerró:. Una conexión que se espera que sea mantenido con vida fue cerrada por el servidor"

he encontrado algunos artículos que indican que el ajuste de mantenimiento de conexión a falso y httpversion a 1.0 resuelve la situación. Estoy descubriendo que no Yeilding exactamente el mismo error, además de que no quiero tomar ese enfoque, ya que no quiero usar la versión 1.0 debido a la forma en que maneja la conexión.

Cualquier sugerencia o ideas son bienvenidas. Voy a tratar a todos ellos hasta que se trabaja!

public ServerResponse PostAttachment(Server server, Database db, Attachment attachment)
    {
        Stream dataStream;
        HttpWebResponse response = null;
        StreamReader sr = null;
        byte[] buffer;
        string json;
        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
        string headerTemplate = "Content-Disposition: form-data; name=\"_attachments\"; filename=\"" + attachment.Filename + "\"\r\n Content-Type: application/octet-stream\r\n\r\n";
        byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(headerTemplate);
        byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");


        HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://" + server.Host + ":" + 
            server.Port.ToString() + "/" + db.Name + "/" + attachment.Document.Id);
        httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
        httpWebRequest.Method = "POST";
        httpWebRequest.KeepAlive = true;
        httpWebRequest.ContentLength = attachment.Stream.Length + headerbytes.Length + boundarybytes.Length;

        if (!string.IsNullOrEmpty(server.EncodedCredentials))
            httpWebRequest.Headers.Add("Authorization", server.EncodedCredentials);

        if (!attachment.Stream.CanRead)
            throw new System.NotSupportedException("The stream cannot be read.");

        // Get the request stream
        try
        {
            dataStream = httpWebRequest.GetRequestStream();
        }
        catch (Exception e)
        {
            throw new WebException("Failed to get the request stream.", e);
        }


        buffer = new byte[server.BufferSize];
        int bytesRead;

        dataStream.Write(headerbytes,0,headerbytes.Length); 

        attachment.Stream.Position = 0;
        while ((bytesRead = attachment.Stream.Read(buffer, 0, buffer.Length)) > 0)
        {
            dataStream.Write(buffer, 0, bytesRead);
        }

        dataStream.Write(boundarybytes, 0, boundarybytes.Length);
        dataStream.Close();

        // send the request and get the response
        try
        {
            response = (HttpWebResponse)httpWebRequest.GetResponse();
        }
        catch (Exception e)
        {
            throw new WebException("Invalid response received from server.", e);
        }

        // get the server's response json
        try
        {
            dataStream = response.GetResponseStream();
            sr = new StreamReader(dataStream);
            json = sr.ReadToEnd();
        }
        catch (Exception e)
        {
            throw new WebException("Failed to access the response stream.", e);
        }

        // close up all our streams and response
        sr.Close();
        dataStream.Close();
        response.Close();

        // Deserialize the server response
        return ConvertTo.JsonToServerResponse(json);
    }
¿Fue útil?

Solución

Después de una considerable cantidad de investigación sobre el tema, he decidido utilizar PUT. Mientras futón utiliza el método POST, que es indocumentado. Para cualquiera que lea esto en el futuro, utilice el método PUT, que le hará la vida mucho más fácil.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top