简体   繁体   中英

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

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?

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

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.

Did you try this :

var client = new HttpClient();
client.DefaultRequestHeaders.Add("Connection", "keep-alive");

It gives this :

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM