C# How to set HttpClient Keep-Alive to false

两盒软妹~` 提交于 2019-12-02 22:17:26

When you set HttpWebRequest.KeepAlive = true the header set is Connection: keep-alive

When you set HttpWebRequest.KeepAlive = false the header set is Connection: close

So you will need

_http.DefaultRequestHeaders.Add("Connection", "close");

Use this code to disable HTTP Keep-Alive on the client:

_http.DefaultRequestHeaders.ConnectionClose = true;

This will set Connection request header to close.

See code below:

HttpClient cli;
...
cli.DefaultRequestHeaders.Add("Connection", "keep-alive");
cli.DefaultRequestHeaders.Add("Keep-Alive", "600");

I hope this can help you, I have tested

_client.DefaultRequestHeaders.Connection.Add("Keep-Alive");

I wrote HttpClientHandler, and in the handler just before the request I deleted the header "Connection". In this case, it sets the default "Connection: keep-alive". Even if before that you put it in the HttpClient by default, set properties, etc. Check your handlers.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!