.NET Zone is brought to you in partnership with:

C# ASP.NET developer who works with MVC but is sometimes known to dabble with WebForms. Passionate coder who cares about his craft. Has a real want to create clean, readable and maintainable code. Obsessed with CI and its effects on a good development team. Pushing the bounds of continuous delivery and studying the advantages it brings to developers. Paul is a DZone MVB and is not an employee of DZone and has posted 25 posts at DZone. You can read more from them at their website. View Full User Profile

Spoofing the Host Entry in a HTTPWebRequest

05.06.2012
| 3900 views |
  • submit to reddit

I had this idea to create a dashboard that would ping different version of a site in order to get the build number. The details are as follows:

www.mysite.com

runs on a local site at 192.x.x.x, a QA environment at 10.x.x.x, a staging environment at 66.x.x.x, and a live environment at 88.x.x.x (these IPs are made up). In order to hit each site, I would usually manually change the host file and then make the web request. This was not a great solution as I hate dealing with host file entries. On experimenting with HTTPWebRequest, I noticed that you can use reflection in order to change the Headers of the Request. The normal code to create a HTTPWebRequest would look as follows:

try
{
    var request = (HttpWebRequest)HttpWebRequest.Create(new Uri("string url"));

    var webresponse = (HttpWebResponse)request.GetResponse();
    var streamReader = new StreamReader(webresponse.GetResponseStream());

    string response = streamReader.ReadToEnd();
}

I was able to spoof the host by changing the host using reflection:

try
{
var request = (HttpWebRequest)HttpWebRequest.Create(new Uri("string IP address"));
request.Headers.GetType().InvokeMember("ChangeInternal",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null,
request.Headers, new object[] { "Host", "Fake host entry" });

var webresponse = (HttpWebResponse)request.GetResponse();

var streamReader = new StreamReader(webresponse.GetResponseStream());

string response = streamReader.ReadToEnd();
}

This allowed me to make multiple requests to different versions of the same site. Using a simple collection of my site objects to build a dashboard that had the following outline:

  Local QA Stage Live
Build Number web_12_4_qa web_12_4_qa web_12_5_stg web_12_4_pro

 

Published at DZone with permission of Paul Stack, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)