建立httpheader连接:保留到小写的"keep-alive"脚本中. [英] Make httpheader Connection: Keep-Alive into lower-case "keep-alive"

查看:117
本文介绍了建立httpheader连接:保留到小写的"keep-alive"脚本中.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试添加新标头的方法:

What I tried it to add new header:

request.Headers.GetType().InvokeMember("ChangeInternal",
    BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
    Type.DefaultBinder, request.Headers, new object[] { "Connection", "keep-alive" }
);

实际上,它会将keep-alive标头添加到Connection中,但是不会替换旧的标头.所以我得到Connection: Keep-Alive,keep-alive.

Actually it adds keep-alive header into Connection but it doesn't replace old one. So I get Connection: Keep-Alive,keep-alive.

我尝试了反射实验,但是没有任何效果.

I tried experimenting with Reflection but didn't got anything working.

对此还有其他类似的问题,但没有解决方案.

There is other similar questions about this but there was no solution.

推荐答案

只需执行以下操作:

request.Headers.Remove("Connection");
request.Headers.Add("Connection", "keep-alive");

不必通过反射设置这些标头. 首先,重要的是删除旧条目,因为如果键已经存在,则对Add的调用会添加另一个值(您看到的结果以逗号分隔).

It's not neccessary to set these headers via reflection. In the first place it's important to remove the old entry as an call to Add adds another value if the key already exists (the result you saw with comma separated values).

最好使用HttpRequestHeader枚举而不是标头名称作为字符串:

It'd be even better to use the HttpRequestHeader Enumeration instead of the header name as string:

request.Headers.Remove(HttpRequestHeader.Connection);
request.Headers.Add(HttpRequestHeader.Connection, "keep-alive");

我的坏.在这种情况下,必须在请求对象上使用明确的Connection属性:

request.Connection = "keep-alive";

仅供参考:还有更多标头必须通过其显式属性进行设置.有关列表,请参阅此页面的备注部分:

FYI: There are some more headers that must be set via their explicit propertries. For a list refer to this page, section remarks: https://msdn.microsoft.com/en-us/library/System.Net.HttpWebRequest%28v=vs.110%29.aspx

好吧,请查看连接属性的源代码,您会看到它限制了这些值的设置:

Well, looking at the connection property's source code, you can see that it restricts setting these values:

bool fKeepAlive = text.IndexOf("keep-alive") != -1;
bool fClose = text.IndexOf("close") != -1;
if (fKeepAlive || fClose)
{
    throw new ArgumentException(SR.GetString("net_connarg"), "value");
}

因此,您有2个选择:

  1. 使用大写字母(我希望使用)大写,因为您没有 real 的理由,因为它是小写字母(例如firefox浏览器." ).正如达林·迪米特洛夫(Darin Dimitrov)所述,标头无论如何都不应该区分大小写.
  2. 以这种方式扩展反射方法,首先删除标头,然后再将其重新设置为小写.
  1. Stick with the upper-case value (which I'd prefer) as anyway you have no real reason for it being lower-case ("So I want to have headers exactly as my for example firefox browser."). And as Darin Dimitrov already stated, headers shouldn't be case-sensitive anyway.
  2. Extend your reflection-approach in that way, that you first remove the header an then set it again in lower-case.

这篇关于建立httpheader连接:保留到小写的"keep-alive"脚本中.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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