HttpWebResponse.ReadTimeout - Timeouts not supported?

James Hutchison picture James Hutchison · Mar 20, 2012 · Viewed 13.1k times · Source

We have an issue where on a single instance of our product we receive an InvalidOperationException exception when we attempt to set the ReadTimeout property of an System.Net.HttpWebResponse object.

This issue is occurring only on a single instance, where we have many multiple live sites without this problem. We've tried to recreate the issue locally, to no avail.

The following code illustrates the issue.

Any ideas are greatly welcome.

Thanks

    private static XmlReader GenerateReaderFromResponse(HttpWebResponse response, HttpWebRequest request)
    {
        Stream responseStream = response.GetResponseStream();
        responseStream.ReadTimeout = request.Timeout; //This is where the exception is generated - System.InvalidOperationException: Timeouts are not supported on this stream.

        using (StreamReader responseReader = new StreamReader(responseStream, System.Text.Encoding.UTF8))
        {
            XmlReaderSettings readerSettings = new XmlReaderSettings();
            readerSettings.ProhibitDtd = false;
            string responseContent = responseReader.ReadToEnd();
            return XmlReader.Create(new StringReader(responseContent), readerSettings);
        }
    }

Answer

ShdNx picture ShdNx · Mar 20, 2012

What you need is the HttpWebRequest.ReadWriteTimeout property.

It specifies the number of milliseconds before the reading (or writing) operation on the response Stream times out, throwing a WebException with Status set to WebExceptionStatus.RequestCanceled.

From the msdn documentation:

The ReadWriteTimeout property is used when writing to the stream returned by the GetRequestStream method or reading from the stream returned by the GetResponseStream method.

Specifically, the ReadWriteTimeout property controls the time-out for the Read method, which is used to read the stream returned by the GetResponseStream method, and for the Write method, which is used to write to the stream returned by the GetRequestStream method.

To specify the amount of time to wait for the request to complete, use the Timeout property.