Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# ContentLength error for Request Stream

I’m trying to get an AWS example (from their website) working, and am getting the following error;

System.Net.ProtocolViolationException: ‘You must write ContentLength
bytes to the request stream before calling [Begin]GetResponse.’

on this line of code;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())

in this function;

public static void CheckResponse(HttpWebRequest request)
{
    Console.WriteLine("\n-- CHECK RESPONCE");
    // Get the response and read any body into a string, then display.

    Console.WriteLine(request.ContentLength); //857

    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            Console.WriteLine("\n-- HTTP call succeeded");
            var responseBody = ReadResponseBody(response);
            if (!string.IsNullOrEmpty(responseBody))
            {
                Console.WriteLine("\n-- Response body:");
                Console.WriteLine(responseBody);                        
            }
        }
        else
            Console.WriteLine("\n-- HTTP call failed, status code: {0}", response.StatusCode);
    }
}

request.ContentLength is 857, so am not sure how this error makes any sense. I tried setting the request.ContentLength to 857 but that causes an error.

Below is the function that calls CheckResponse()

public static void InvokeHttpRequest(Uri endpointUri,
                                             string httpMethod,
                                             IDictionary<string, string> headers,
                                             string requestBody)
        {
            try
            {
                var request = ConstructWebRequest(endpointUri, httpMethod, headers);

                if (!string.IsNullOrEmpty(requestBody))
                {
                    var buffer = new byte[8192]; // arbitrary buffer size                        
                    var requestStream = request.GetRequestStream();
                    using (var inputStream = new MemoryStream(Encoding.UTF8.GetBytes(requestBody)))
                    {
                        var bytesRead = 0;
                        while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            requestStream.Write(buffer, 0, bytesRead);
                        }
                    }
                }
                CheckResponse(request);
            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.ToString());
                using (var response = ex.Response as HttpWebResponse)
                {
                    if (response != null)
                    {
                        var errorMsg = ReadResponseBody(response);
                        Console.WriteLine("\n-- HTTP call failed with exception '{0}', status code '{1}'", errorMsg, response.StatusCode);
                    }
                }
            }
        }

>Solution :

Based on very quick scan of the code – looks like you aren’t flushing the requestStream. Wrap it in using block to ensure it is flushed.

var requestStream = request.GetRequestStream();

should be

using(var requestStream = request.GetRequestStream()) ....

The bytes aren’t necessarily written until the stream is disposed or manually flushed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading