Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent HttpClient from sending the Connection header

HttpClient includes this as 'Keep-Alive' by default. I've been able to set it to 'Close' using httpClient.DefaultRequestHeaders.ConnectionClose = true; but how do I omit it altogether?

like image 490
Matthew Whitwam Avatar asked Nov 21 '17 11:11

Matthew Whitwam


People also ask

Which HTTP header will prevent a connection from being closed after a server sends its response?

Therefore in HTTP 1.0 the client can tell the server that it will keep the connection open by using the connection: keep-alive header.

What does it mean when an HTTP query has a header field of connection keep-alive?

The Connection general header controls whether the network connection stays open after the current transaction finishes. If the value sent is keep-alive , the connection is persistent and not closed, allowing for subsequent requests to the same server to be done.

How do I pass HttpClient headers?

Adding User-Agent header to single HttpRequest If you wish to add the User-Agent header to a single HttpRequestMessage , this can be done like this: var httpClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.

How do I close keep-alive connection?

Use “KeepAlive On” to enable it. To disable, just use “KeepAlive Off”. It sets the maximum number of requests for every Keep-Alive connection. A value of 100 is normally good enough for almost any scenario.


1 Answers

I've seen this asked before and to my knowledge no one (not even the great Jon Skeet) has come up with a way to avoid sending the Connection header in the HttpClient or HttpWebRequest worlds without completely reinventing the wheel. It's happening somewhere very deep down in the weeds.

ConnectionClose is nullable, but setting it to null on both HttpClient.DefaultRequestHeaders AND HttpRequestMethod.Headers still results in a Connection: Keep-Alive header being sent.

To summarize:

  • HttpRequestHeaders.ConnectionClose = true => Connection: close
  • HttpRequestHeaders.ConnectionClose = false => Connection: Keep-Alive
  • HttpRequestHeaders.ConnectionClose = null => Connection: Keep-Alive

  • HttpWebRequest.KeepAlive = true => Connection: Keep-Alive

  • HttpWebRequest.KeepAlive = false => Connection: close

(HttpWebRequest.KeepAlive is not nullable)

like image 153
Todd Menier Avatar answered Sep 28 '22 17:09

Todd Menier