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" }
);
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.
Just do the following:
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).It'd be even better to use the HttpRequestHeader Enumeration instead of the header name as string:
Edit:
My bad. There's an explicit
Connection
property on the request-object which must be used in that case: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
Edit2:
Well, looking at the connection property's source code, you can see that it restricts setting these values:
So you have 2 options: