尝试从FitNesse REST URI读取响应时出现连接关闭错误

时间:2009-11-10 15:55:45

标签: c# .net rest fitnesse

你遇到过这个问题吗?我运行的代码与this previous question非常相似,当处于nUnitTest模式且URI包含“/?test& format = xml”时,nUnit测试失败,并且IOException,“无法从传输连接中读取数据:连接已关闭。“

然而,当时正在运行的Fiddler跟踪显示了我期望的xml。

我已经完全(几乎)重新创建了请求标头,因为它们是在通过浏览器发送时发送的。

最后,如果我从URI中取消“/?test& format = xml”,我会得到我原本预期的html。

消息来源代码:

    public virtual bool Run()
    {
        var request = CreateRequest();
        var response = GetResponse(request);
        var responseString = ReadResponse(response);
        this.SetResults(responseString);
        return this.IsSuccessful;
    }

    protected internal virtual HttpWebRequest CreateRequest()
    {
        var address = TestConfig.Address;

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

        request.Accept = "*/*";
        request.UseDefaultCredentials = true;
        request.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);

        return request;
    }

    protected internal virtual HttpWebResponse GetResponse(HttpWebRequest request)
    {
        var response = (HttpWebResponse) request.GetResponse();

        return response;
    }

    protected internal virtual string ReadResponse(HttpWebResponse response)
    {
        var stream = response.GetResponseStream();
        var responseString = ReadResponse(stream);

        stream.Close();
        response.Close();

        return responseString;
    }

    protected internal virtual string ReadResponse(Stream stream)
    {
        var reader = new StreamReader(stream);
        var responseString = reader.ReadToEnd();
        return responseString;
    }

1 个答案:

答案 0 :(得分:0)

错误消息“无法从传输连接读取数据:连接已关闭。”并没有真正与你看到Fiddler获得一个html响应体的事实相关。

检查HttpWebResponse的StatusCode(如果可以,应为200),也将请求包装在try / catch块中(例如来自http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.statuscode(v=vs.80).aspx

try 
   {    
        // Creates an HttpWebRequest for the specified URL. 
        HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
        // Sends the HttpWebRequest and waits for a response.
        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse(); 
        if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
           Console.WriteLine("\r\nResponse Status Code is OK and StatusDescription is: {0}",
                                myHttpWebResponse.StatusDescription);
        // Releases the resources of the response.
        myHttpWebResponse.Close(); 

    } 
catch(WebException e) 
   {
        Console.WriteLine("\r\nWebException Raised. The following error occured : {0}",e.Status); 
   }
catch(Exception e)
{
    Console.WriteLine("\nThe following Exception was raised : {0}",e.Message);
}

如果你正在快速创建和处理HttpWebRequest对象,你可能会让套接字在关闭时进入time_wait状态,那么在它完全关闭之前你不能再次重新打开它。如果是这种情况,请查看使用其他端口或更改连接所用的时间。