Unknown
Unknown

Reputation: 46821

C# get rid of Connection header in WebClient

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?

Upvotes: 13

Views: 12444

Answers (2)

Redha
Redha

Reputation: 181

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

Upvotes: 16

Jon Skeet
Jon Skeet

Reputation: 1503280

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.

Upvotes: 5

Related Questions