Pavel
Pavel

Reputation: 111

Remove Host header in HttpClient request

I'm using the HttpClient class to send some data to specific host. I just want to send a pure header without any additional lines in it like ("Host: http"). So this line is the last to be removed from the header, but I don't know how.

The code:

HttpRequestMessage msg = new HttpRequestMessage(HttpMethod.Post, aUrl);
msg.Headers.Clear();
msg.Headers.Remove("Host");
msg.Headers.ExpectContinue = false;
Encoding encoding = ConfiguratorASUST.Instance.Encoding ?? Encoding.GetEncoding(ConfiguratorASUST.ENCODING_DEFAULT);
msg.Content = new StringContent(aStr, encoding);
_client.SendAsync(msg);

The result header in Fiddler:

POST http://http//localhost.fiddler:60001/POS/POSTELESPIS HTTP/1.1
Content-Type: text/plain; charset=windows-1251
Host: http

This line Host: http needs to be removed from the message's header. But how on earth can I do that?! I tried the following:

msg.Headers.Clear();
msg.Headers.Remove("Host");

To no avail. Actually I also see the header Proxy-Connection: Keep-Alive being added.

Upvotes: 2

Views: 13685

Answers (1)

CodeCaster
CodeCaster

Reputation: 151594

If you carefully inspect your URL, it looks like your it is wrong anyway: http://http// - is your host really named http, and do you really need two slashes after it? Anyway if you fix that, the Host header will carry localhost.fiddler:60001.

By removing the Host header, you're essentially downgrading your request to HTTP/1.0.

You can set the HTTP version in the HttpRequestMessage as explained in Set HTTP protocol version in HttpClient:

msg.Version = HttpVersion.Version10;

But when using Fiddler, it acts as a proxy, and forwards your request as an HTTP/1.1 request - including the host header again. You can also alter the request in Fiddler. This is explained in How do I prevent fiddler from insering "Host" HTTP header?, but note the bold text, emphasis mine:

Per the RFC, as a HTTP/1.1 proxy, Fiddler is required to add a Host header.

It's not clear why this is problematic-- any server that has a problem with this is, by definition, buggy and should be fixed.

You can remove the header if you'd like (although doing so can cause problems elsewhere). Click Rules > Customize Rules. Scroll to OnBeforeRequest and add the following:

if (oSession.oRequest.headers.HTTPVersion == "HTTP/1.0")
{
    oSession["x-overridehost"] = oSession.host;
    oSession.oRequest.headers.Remove("Host");
}

Upvotes: 6

Related Questions