1

I want my http get request to fail if it takes more than 10 seconds by timint out.

I have this:

var request = (HttpWebRequest)WebRequest.Create(myUrl);

request.Method = "GET";
request.Timeout = 1000 * 10; // 10 seconds

HttpStatusCode httpStatusCode = HttpStatusCode.ServiceUnavailable;

using (var webResponse = (HttpWebResponse)request.GetResponse())
{
    httpStatusCode = webResponse.StatusCode;
}

It doesn't seem to timeout when I put a bad URL in the request, it just keeps going and going for a long time (seems like minutes).

WHy is this?

Oded
  • 489,969
  • 99
  • 883
  • 1,009
loyalflow
  • 14,275
  • 27
  • 107
  • 168

2 Answers2

2

If you are doing it in a web project, make sure the debug attribute of the system.web/compilation tag in the Web.Config file is set to "false".

If it is a console application or such, compile it in "Release" mode.

A lot of timeouts are ignored in "Debug" mode.

Dmitry S.
  • 8,373
  • 2
  • 39
  • 49
1

Your code is probably performing a DNS lookup on the bad URL which takes a minimum of 15 seconds.

According to the documentation for HttpWebRequest.Timeout

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.

You can perform a DNS Lookup using Dns.GetHostEntry but it looks like it will take 5 seconds by default.

JoshVarty
  • 9,066
  • 4
  • 52
  • 80