13

I'm using the C# using the WebClient().

I was testing out what headers are sent, and I noticed that the following header is automatically added.

Connection : Keep-Alive

Is there any way to remove this?

Unknown
  • 45,913
  • 27
  • 138
  • 182

2 Answers2

16

I had ran into the same issue this morning. Following on Jon Skeet's hint, it can be achieved by passing HttpWebRequest to WebClient by inheriting it:

class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        WebRequest request = base.GetWebRequest(address);
        if (request is HttpWebRequest)
        {
            (request as HttpWebRequest).KeepAlive = false;
        }
        return request;
    }
}

Now sent headers will include Connection : close

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Redha
  • 181
  • 1
  • 3
  • Let me suggest an updated version since C# has moved a little since ;-) `class MyWebClient : WebClient { protected override WebRequest GetWebRequest(Uri address) { WebRequest request = base.GetWebRequest(address); if (request is HttpWebRequest wr) { wr.KeepAlive = false; } return request; } }` – Marcus Pierce Jan 07 '21 at 06:17
5

Use HttpWebRequest instead of WebClient (it's slightly less convenient, but not by very much) and set the KeepAlive property to false.

I haven't tested this - it's possible that it'll just change the value of the Connection header instead of removing it - but it's worth a try. The docs for the Connection property at least suggest that it only adds Keep-Alive.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 5
    One thing to note is that doing this doesn't *remove* the Connection header, although it does change it from "Connection: Keep-Alive" to "Connection: Close". – Scott Mitchell Oct 16 '09 at 16:57