Matthew Whitwam
Matthew Whitwam

Reputation: 351

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?

Upvotes: 15

Views: 11036

Answers (1)

Todd Menier
Todd Menier

Reputation: 39369

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)

Upvotes: 23

Related Questions