问题
I have a task where I need to be able to send Connection: keep-alive header the same way as it is done by the Firefox browser (notice that keep-alive has to be all lower-case):
"Connection: keep-alive"
However, I had no luck in achieving it using HttpClient. No matter what I try, the request always have
"Connection: Keep-Alive"
Here is an example code:
var client = new HttpClient();
var request = new HttpRequestMessage()
{
RequestUri = new Uri("http://www.someURI.com"),
Method = HttpMethod.Get,
};
request.Headers.Connection.Clear(); // No need to do it as it is empty anyway
request.Headers.Connection.Add("keep-alive"); // Still results in "Keep-Alive"
var task = client.SendAsync(request);
Another attempt:
var client = new HttpClient();
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Connection.Add("keep-alive"); // Still results in "Keep-Alive"
string result = await client.GetStringAsync("http://www.someURI.com");
There is an answer about how it can be done in HttpWebRequest: How to send lower-case Keep-Alive header through HttpWebRequest
Would something similar be possible in HttpClient?
回答1:
This problem is only present when you run code on Windows platform. It is present in .Net and .Net Core 2.0. The underlying reason for this lies in win32 library "winhttp.dll" which contains hardcoded string for "Keep-Alive", so if you need to get it working on windows, you will need to do something about this dll.
The good news is that this issue does not affect Linux platforms running Mono or .NET Core 2.0
回答2:
It does not matter for HTTP Server whether "keep-alive" is upper case or not. Just add the text "keep-alive" or "Keep-Alive" or "KEEP_ALIVE" then should be treated same.
hope this helps.
回答3:
Did you try this :
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Connection", "keep-alive");
It gives this :
来源:https://stackoverflow.com/questions/37005125/how-to-set-connection-keep-alive-header-in-lower-case-through-httpclient