How to set “Connection: keep-alive” header in lower case through HttpClient?

佐手、 提交于 2020-01-01 11:48:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!