2012-04-12 156 views
0

我在Win 7 IIS上运行一个非常简单的Web应用程序(Asp.Net MVC3)。 我有一个非常简单的HTTP GET API,它返回hello world。IIS 7向浏览器正确发送GET请求,但为API请求发送超时异常

呼唤:

http://localhost/helloworld 

返回:

Hello World! 

这工作完全在浏览器中。 但是,当我写它试图使用Web客户端来拉这个网址的应用程序,我得到以下错误:

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

我的代码如下

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

我的IIS设置为如下 enter image description here

我该看什么?我一直在这里待了好几个小时,但我没有办法尝试!任何帮助将非常感激!

谢谢。

回答

0

我终于明白了问题出在哪里,而不是IIS特定的问题 - 我倾向于这个问题,结果是我写的代码存在问题。

在此添加详细信息,以免别人遇到类似问题。

我在我的代码中使用了以下方法将请求的响应作为JSON对象发送。

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 
} 

在周围挖一点,我发现,我们应该做一个Response.Close()。

对此的更好解释是here。 一旦我删除该行,它开始工作完美 - 无论是在我的消费应用程序以及网络浏览器等。

如果您将阅读上面的链接,您将清楚地理解为什么我们不应该使用响应.Close() - 所以我不会去描述。今天学到了一件新事物。

0

我怀疑这是因为Web客户端不发送一些HTTP头:

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

尝试使用HttpWebRequest的替代。 http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.aspx

+0

感谢您的快速响应。我尝试使用HTTPWebRequest。我的代码几乎是这样的:http://forums.asp.net/post/2930891.aspx 然而,在我做的地方:readStream.ReadToEnd(),我得到同样的问题(数据不能在连接关闭时下载)。我认为这是一些IIS特定的事情。 – saurabhj 2012-04-13 06:36:43