C# 去掉 WebClient 中的 Connection 头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/896207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# get rid of Connection header in WebClient
提问by Unknown
I'm using the C# using the WebClient().
我正在使用 C# 使用 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?
有什么办法可以去掉这个吗?
回答by Jon Skeet
Use HttpWebRequest
instead of WebClient
(it's slightlyless convenient, but not by very much) and set the KeepAlive
property to false
.
使用HttpWebRequest
代替WebClient
(稍微不太方便,但不是很方便)并将KeepAlive
属性设置为false
.
I haven't tested this - it's possiblethat 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 suggestthat it only adds Keep-Alive.
我还没有测试过这个 - 它可能只是改变 Connection 标头的值而不是删除它 - 但值得一试。该Connection
属性的文档至少表明它只添加了 Keep-Alive。
回答by Redha
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:
我今天早上遇到了同样的问题。按照 Skeet 的提示,可以通过继承来传递HttpWebRequest
to来实现WebClient
:
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
现在发送的标头将包括Connection : close