StuffHappens
StuffHappens

Reputation: 6557

When does WebRequest.GetResponse() set Connection to "Keep-Alive" c#

I have the following function

private byte[] Function(string url)
{
    HttpWebRequest webRequest= (HttpWebRequest)WebRequest.Create(url);
    webRequest.AddRange(0, 200);
    webRequest.Method = "GET";
    webRequest.KeepAlive = true;

    byte[] buffer = new byte[200];
    using (var webResponse =  webRequest.GetResponse())
    using (Stream webResponseStreem = webResponse.GetResponseStream())
    {
        webResponseStreem.Read(buffer, 0, 200);
    }

    return buffer;
}

and I call it from different part of my application. Sometimes the result that I get is not what I expect. I noticed that sometimes the call webRequest.GetResponse() sets webRequest.Connection to "Keep-Alive" and sometimes does not. What does it depend on?

Upvotes: 0

Views: 3720

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038810

I don't know what controls whether this header should be sent or not, but according to the documentation:

When using HTTP/1.1, Keep-Alive is on by default. Setting KeepAlive to false may result in sending a Connection: Close header to the server.

So if you are using HTTP/1.1 it shouldn't matter whether the header is sent or not. If there is no Connection: close header the server should assume a persistent connection.

Upvotes: 1

Related Questions