C# How to set HttpClient Keep-Alive to false

前端 未结 5 1672
一生所求
一生所求 2020-12-14 01:40

I had a low performance problem with HTTP requests on .NET. The HTTP GET request to a REST API on the localhost took about 500 ms to complete. I spent a lot of time to fix i

相关标签:
5条回答
  • 2020-12-14 02:18

    I hope this can help you, I have tested

    _client.DefaultRequestHeaders.Connection.Add("Keep-Alive");
    
    0 讨论(0)
  • 2020-12-14 02:19

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

    _http.DefaultRequestHeaders.ConnectionClose = true;
    

    This will set Connection request header to close.

    0 讨论(0)
  • 2020-12-14 02:21

    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");
    
    0 讨论(0)
  • 2020-12-14 02:23

    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.

    0 讨论(0)
  • 2020-12-14 02:31

    See code below:

    HttpClient cli;
    ...
    cli.DefaultRequestHeaders.Add("Connection", "keep-alive");
    cli.DefaultRequestHeaders.Add("Keep-Alive", "600");
    
    0 讨论(0)
提交回复
热议问题