简体   繁体   中英

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?

I had ran into the same issue this morning. Following on 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

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.

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