Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I reuse HttpWebRequest without disconnecting from the server?

I'm trying to debug a specific issue with my ASP.NET application. The client runs the following code:

void uploadFile( string serverUrl, string filePath )
{
    HttpWebRequest request = (HttpWebRequest)HttpWebRequest.
        Create( serverUrl );
    CredentialCache cache = new CredentialCache();
    cache.Add( new Uri( serverUrl ), "Basic", new NetworkCredential( "User", "pass" ) );
    request.Credentials = cache;
    request.Method = "POST";
    request.ContentType = "application/octet-stream";
    request.Timeout = 60000;
    request.KeepAlive = true;

    using( BinaryReader reader = new BinaryReader( 
        File.OpenRead( filePath ) ) ) {

        request.ContentLength = reader.BaseStream.Length;
        using( Stream stream = request.GetRequestStream() ) {
            byte[] buffer = new byte[1024];
            while( true ) {
                int bytesRead = reader.Read( buffer, 0, buffer.Length );
                if( bytesRead == 0 ) {
                    break;
                }
                stream.Write( buffer, 0, bytesRead );
            }
        }
    }

     HttpWebResponse result = (HttpWebResponse)request.GetResponse();
     //handle result - not relevant
 }

and Write() throws an exception with "Unable to write data to the transport connection: An established connection was aborted by the software in your host machine." text. I used System.Net tracing and found that something goes wrong when I send the request with Content-Length set.

Specifically if I omit everything that is inside using statement in the code above the server promptly replies with WWW-Authenticate and then the client reposts the request with WWW-Authenticate and everything goes fine except the file in not uploaded and the request fails much later.

I'd like to do the following: send an request without data, wait for WWW-Authenticate, then repeat it with WWW-Authenticate and data. So I tried to modify the code above: first set all the parameters, then call GetResponse(), then do sending, but when I try to set ContentLength property an exception is thrown with "This property cannot be set after writing has started" text.

So HttpWebRequest seems to be non-reusable.

How do I reuse it for resending the request without closing the connection?

like image 999
sharptooth Avatar asked Feb 08 '11 13:02

sharptooth


People also ask

Should I dispose HttpWebRequest?

HttpWebRequest does not implement IDisposable so it does not require disposing. just set the httprequest object to null once your done with it.

What is the difference between HttpWebRequest and WebRequest?

In a nutshell, WebRequest—in its HTTP-specific implementation, HttpWebRequest—represents the original way to consume HTTP requests in . NET Framework. WebClient provides a simple but limited wrapper around HttpWebRequest. And HttpClient is the new and improved way of doing HTTP requests and posts, having arrived with .

What is the use of HttpWebRequest in C#?

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.


2 Answers

You don't reuse a request - as the name suggests, it's one request. However, if you issue multiple requests for the same host, .NET will reuse the underlying network connection by default.

Note that you do need to dispose of the WebResponse returned by request.GetResponse - otherwise the underlying infrastructure won't know that you're actually done with it, and won't be able to reuse the connection.

(As an aside, why are you using BinaryReader? Just use the stream returned by File.OpenRead directly.)

like image 60
Jon Skeet Avatar answered Sep 21 '22 19:09

Jon Skeet


In addition to the Jon Skeet's answer, you don't need to manually set the ContentLength property. HttpWebRequest will auto calculate and populate that property.

like image 28
Genady Sergeev Avatar answered Sep 21 '22 19:09

Genady Sergeev