sedavidw
sedavidw

Reputation: 11691

HttpClient is modifying my original request to change domains

I have some code that is making a Server2Server call using an HttpClient. Here is some quick code

Code to make a request

    private HttpRequestMessage GetRequest(Uri uri, NameValueCollection headers)
    {
        var method = HttpMethod.Get;
        var request = new HttpRequestMessage(method, uri);
        foreach (string v in headers)
        {
            var success = request.Headers.TryAddWithoutValidation(v, headers[v]);

            if (!success)
            {
                // log something ( no logs are appearing )
            }
        }
        return request;
    }

Code to make the request

private void AsyncCallUrl(Uri url, NameValueCollection headers)
{
    object result1 = null;
    var handler = new HttpClientHandler() { AllowAutoRedirect = false };
    using (HttpClient client = new HttpClient(handler))
    {
        var request = GetRequest(url, headers);
        using (HttpResponseMessage response = client.SendAsync(request).Result) // when this line is executed the request object's domain is changed to something else
        {
            using (HttpContent content = response.Content)
            {
                result1 = content.ReadAsStringAsync().Result;
            }
        }
    }

I've verified that the request object is created appropriately with the proper domain. I've also verified that the network traffic is going to the wrong domain, even the request object shows the new bad domain. What I don't is why this is happening. I've even set the AllowAutoRedirect to false

NOTE: As a note I notice that if I use GetAsync instead of SendAsync the domain change doesn't happen. However this is not an ideal solution as in order to add headers I would need to add them to the HttpClient itself and this code lives on an IIS server and I don't want to make a new client for every request

Upvotes: 2

Views: 2119

Answers (1)

spender
spender

Reputation: 120480

So, with SendAsync the value of the Host header of the request is determined by the uri parameter... However it is possible to override the Host header through the Headers property of the request.

It's highly likely that the NameValueCollection headers that you are blindly injecting into the request's headers contains an entry for Host which is different to that which you supplied in the Uri.


As an aside, this behaviour can be useful, if (for instance) you were to discover that the DNS performance of HttpWebRequest (the business end of HttpClient on Windows) is sub-standard. I've bypassed .Net/Windows DNS by using a third party library to look up the IP of the host, rewriting the Uri to use the IP address in place of the host name, then setting the Host header on the outgoing request back to the original host name.

Upvotes: 4

Related Questions