I need to inspect some HTTP headers and so I'm using C#'s HttpWebRequest
and HttpWebResponse
classes.
I'm developing using Visual Studio 2012 and would like to test out the request and response on my localhost so I can see what kind of headers I'm dealing with (I use devtools in Chrome so I can see there, but I want to make sure my code is returning the proper values). When I simply put in http://localhost:[Port]/
it doesn't connect.
I can see that it repeatedly is making a request to the server and eventually I get the exception WebException: The Operation has timed out
. If I add request.KeepAlive = false'
then I get the exception WebException: Unable to connect to the remote server
.
So I'm wondering:
- Is something wrong with my code? (see below)
- How can I test
HttpWebRequest
andHttpWebResponse
on localhost?
I've tried using the IP address in place of "localhost" but that didn't work (ex http://127.0.0.1:[port]/
)
Code:
public class AuthorizationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
string url = "http://127.0.0.1:7792/";
string responseString;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//request.KeepAlive = false;
//request.AllowAutoRedirect = false;
System.Diagnostics.Debug.Write(request);
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
responseString = reader.ReadToEnd();
System.Diagnostics.Debug.Write(responseString);
}
}
}
catch (Exception e)
{
System.Diagnostics.Debug.Write(e.Message);
System.Diagnostics.Debug.Write(e.Source);
}
}
}