15

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?

H H
  • 263,252
  • 30
  • 330
  • 514
Matthew Whitwam
  • 351
  • 3
  • 8
  • May I ask why you want to do this? The header determines how client and server communicate with each other. – poke Nov 21 '17 at 11:09
  • `httpClient.KeepAlive = false` doesn't do the trick? – Rabban Nov 21 '17 at 11:14
  • @poke while trying to troubleshoot problems connecting to the poloniex trading api, I compared what I'm sending to what a working PHP app is sending and the inclusion of this header was the only difference I could see. I recognise that it's "meant" to be there, but I need to eliminate it as a potential cause of my issue. – Matthew Whitwam Nov 21 '17 at 11:55
  • @Rabban `'System.Net.Http.HttpClient' does not contain a definition for 'KeepAlive'` – Matthew Whitwam Nov 21 '17 at 11:57
  • Ok, ended up that my problem was unrelated, but I'm still curious whether or not this is possible. – Matthew Whitwam Nov 21 '17 at 15:04
  • 4
    This is a good question, and troubleshooting is a very legitimate reason, so why the downvote I have no idea. +1 – Todd Menier Nov 21 '17 at 16:22

1 Answers1

22

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)

Todd Menier
  • 37,557
  • 17
  • 150
  • 173