简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM