Rhino
Rhino

Reputation: 31

Proper way of reading from a HttpWebResponse and .NET 4.0 Framework

We are currently experiencing a problem reading a ResponseStream that we have had no issues with in the past. Since adding .NET 4.0 Framwework to our server last night and assigning IIS to use the new framework we are experiencing a few different exceptions when trying to read the responseStream using the following statement (responseStream = httpResponse.GetResponseStream();). Everything up to that point works completely fine. So, I am looking for changes/improvements on how to read from the response. I have pasted the code below that we are using and the exceptions we are experiencing.

Our environment is:

.NET Framework 4.0 Windows Server 2003

THE CODE:

        HttpWebResponse httpResponse;
        Stream responseStream;
        //Accept All Certificate Policy 
        ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };

        HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri(theUrl));
        httpRequest.Method = "POST";
        httpRequest.KeepAlive = false;
        httpRequest.Timeout = timeOut;


        try
        {
            httpResponse = (HttpWebResponse)httpRequest.GetResponse();
            responseStream = httpResponse.GetResponseStream();
        }

THE EXCEPTIONS:

'httpResponse.GetResponseStream().Length' threw an exception of type 'System.NotSupportedException' long {System.NotSupportedException}

'httpResponse.GetResponseStream().Position' threw an exception of type 'System.NotSupportedException' long {System.NotSupportedException}

{"This stream does not support seek operations."} System.SystemException {System.NotSupportedException}


Regards,

Mike

Upvotes: 3

Views: 5887

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500595

You haven't shown the bit of code which tries to use the length - but basically, you aren't guaranteed that you'll know the length of the stream. The server may not have given a content-length header.

If you need to mess with the stream, it's probably best to just copy all the data into a MemoryStream. With .NET 4, that's really easy:

MemoryStream ms = new MemoryStream();
responseStream.CopyTo(ms);

If you don't actually need the length for anything (e.g. you just want to load the results as an XML document) then just read from the stream without calling Length.

Note that it's generally good practice to declare variables at the point of initialization if possible - and you should use using statements for the web response and the response stream.

Upvotes: 6

Related Questions