I am writing some C# 2.0 code which must do basic HTTP GETs and POSTs. I am using System.Net.HttpWebRequest to send both types of request and System.Net.HttpWebResponse to receive both. My code for GET looks like:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Format("{0}?{1}",
URLToHit,
queryString));
request.Method = "GET";
request.Timeout = 1000; // set 1 sec. timeout
request.ProtocolVersion = HttpVersion.Version11; // use HTTP 1.1
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
catch(WebException e)
{
//if I do anything except swallow the exception here, I end up in some sort of endless loop in which the same WebException keeps being re-thrown by the GetResponse method. The exception is always right (ie: in cases when I'm not connected to a network, it gives a timed out error, etc...), but it should not be re-thrown!
}
And my POST code is very similar.
The last line works fine when URLToHit returns a HTTP status 200, but in any other circumstance (ie: non 200 HTTP status, no network connectivity, etc...), a System.Net.WebException is thrown (which is expected, according to MSDN docs). However, my code never makes progress past that line.
When I attempt to debug this, I find that I can't step over or continue past that last line. When I try to do so, the request is re-issued and the exception re-thrown.
Any ideas on what I can do to make the request only be issued once? I've never seen anything like this happen in any exception based code, and I'm out of ideas. Nothing like this happens in any other parts of my code, just the parts that deal with System.Net functionality and constructs.
Thanks!
(Update: added try/catch around the GetRequest method)