如何设置“连接:保持活动"?标头通过HttpClient以小写形式显示? [英] How to set "Connection: keep-alive" header in lower case through HttpClient?

查看:92
本文介绍了如何设置“连接:保持活动"?标头通过HttpClient以小写形式显示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个任务需要发送Connection:keep-alive标头,方法与Firefox浏览器相同(请注意,keep-alive必须全部为小写):

"Connection: keep-alive"

但是,我没有运气使用HttpClient实现它.不管我尝试什么,请求总是有

"Connection: Keep-Alive"

这是示例代码:

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);

另一种尝试:

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");

有一个关于如何在HttpWebRequest中完成的答案:解决方案

在Windows平台上运行代码时,仅存在此问题.它存在于.Net和.Net Core 2.0中.造成这种情况的根本原因在于win32库"winhttp.dll",其中包含"Keep-Alive"的硬编码字符串,因此,如果需要使其在Windows上运行,则需要对此dll做一些操作.

好消息是此问题不会影响运行Mono或.NET Core 2.0的Linux平台

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

这篇关于如何设置“连接:保持活动"?标头通过HttpClient以小写形式显示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆