How to perform a fast web request in C#

Morten Christiansen picture Morten Christiansen · Jul 13, 2009 · Viewed 35.4k times · Source

I have a HTTP based API which I potentially need to call many times. The problem is that I can't get the request to take less than about 20 seconds, though the same request made through a browser is near instantaneous. The following code illustrates how I have implemented it so far.

WebRequest r = HttpWebRequest.Create("https://example.com/http/command?param=blabla");
var response = r.GetResponse();

One solution would be to make an asynchronous request but I would like to know why it takes so long and if I can avoid it. I have also tried using the WebClient class but I suspect it uses a WebRequest internally.

Update:

Running the following code took about 40 seconds in Release Mode (measured with Stopwatch):

WebRequest g = HttpWebRequest.Create("http://www.google.com");
var response = g.GetResponse();

I'm working at a university where there might be different things in the network configuration affecting the performance, but the direct use of the browser illustrates that it should be near instant.

Update 2:

I uploaded the code to a remote machine and it worked fine so the conclusion must be that the .NET code does something extra compared to the browser or it has problems resolving the address through the university network (proxy issues or something?!).

Answer

James Roland picture James Roland · Sep 7, 2010

This problem is similar to another post on StackOverflow: Stackoverflow-2519655(HttpWebrequest is extremely slow)

Most of the time the problem is the Proxy server property. You should set this property to null, otherwise the object will attempt to search for an appropriate proxy server to use before going directly to the source. Note: this property is turn on by default, so you have to explicitly tell the object not to perform this proxy search.

request.Proxy = null;
using (var response = (HttpWebResponse)request.GetResponse())
{
}