0

I am running a very simple Web application (Asp.Net MVC3) on Win 7 IIS. I have a very simple HTTP GET API which returns hello world.

Calling:

http://localhost/helloworld

Returns:

Hello World!

This works perfectly over a browser. But when I write an app which tries to pull this URL using a webclient, I get the following error:

{"Unable to read data from the transport connection: The connection was closed."}

My Code is as follows

WebClient web = new WebClient();
var response = web.DownloadString("http://localhost/helloworld");

My IIS Settings are as follows enter image description here

What should I be looking at? I have been at this for hours and I have run out of options to try! Any help will be really appreciated!

Thanks.

saurabhj
  • 2,357
  • 2
  • 24
  • 34

2 Answers2

0

I suspect it's because WebClient does not send some of the HTTP headers:

A WebClient instance does not send optional HTTP headers by default. If your request requires an optional header, you must add the header to the Headers collection. For example, to retain queries in the response, you must add a user-agent header. Also, servers may return 500 (Internal Server Error) if the user agent header is missing. http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.80).aspx

Try using HttpWebRequest instead. http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

Hector Correa
  • 26,290
  • 8
  • 57
  • 73
  • Thanks for your quick response. I tried using the HTTPWebRequest instead. My code is almost the same as this: http://forums.asp.net/post/2930891.aspx However at the place where I do: readStream.ReadToEnd (), I get the same issue (Data could not be downloaded as the connection was closed). I think this one is some IIS specific thing. – saurabhj Apr 13 '12 at 06:36
0

I finally figured out what the issue was and instead of it being an IIS specific issue - which I was leaning towards, it turned out to be an issue with the code that I wrote.

Adding details here incase someone else runs into a similar problem.

I had the following method in my code which I was using to send the response of the request as a JSON object.

private void sendJsonResult(string result) {
    Response.StatusCode = 200;
    Response.Headers.Add("Content-Type", "application/json; charset=utf-8");
    Response.Flush();
    Response.Write(result);
    Response.End();
    Response.Close();    // <-- This is the problem statement
}

On digging around a bit, I found out that we should not be doing a Response.Close().

A better explanation of this is here. Once I removed that line, it started working perfectly - both in my consuming app as well as the web browser, etc.

If you will read the link above, you will clearly understand why we should not be using a Response.Close() - so I will not go into that description. Learnt a new thing today.

Community
  • 1
  • 1
saurabhj
  • 2,357
  • 2
  • 24
  • 34