我在VS2010,FrameWork 4.0上使用C#。 我寫了一個控制檯應用程序,它依次發出兩個Http-Post調用。 第二個調用在輸入中使用第一個返回的內容。 那麼,當我在調試模式下運行應用程序,使用斷點一步一步(F10),一切正常。 但是,如果我刪除了斷點並按下「F5」,當我的代碼在SECOND Http-Post調用中執行「webRequest.getResponse()」時可能會因爲超時而收到異常,因爲該錯誤大約需要60秒出現。我第二次在HttpPost中使用「getResponse()」,它只能一步一步地調試
例外情況是:ErrorCode 10054 - 連接被遠程主機強制關閉。
這是使用我的應用程序的類(控制檯應用程序調用方法「搜索」):
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;
namespace MyNamespace
{
public class MyClass
{
private string SearchId { get; set; }
private string XmlOutputSearch { get; set; }
public MyClass()
{
SearchId = "";
XmlOutputSearch = "";
}
public string Search()
{
StartSearch();
CheckResults();
return XmlOutputSearch;
}
public void StartSearch()
{
string sInput = "[myStartSearchXmlRequest]";
string sOutput = HttpPost(sInput);
XmlDocument myXmlDoc = new XmlDocument();
myXmlDoc.LoadXml(sOutput);
SearchId = myXmlDoc.SelectSingleNode("//SearchId").InnerXml;
}
public void CheckResults()
{
string sInput = "[myCheckResultsXmlRequest using SearchId]";
XmlOutputSearch = HttpPost(sInput);
}
private string HttpPost(string parameters)
{
try
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("[myURI]");
webRequest.ContentType = "text/xml";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
throw ex;
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
// Here I get the exception, on webRequest.GetResponse(), when HttpPost is called
// by CheckResults, if not in Step-By-Step mode
using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
{
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string sReturn = sr.ReadToEnd().Trim();
sr.Close();
webResponse.Close();
webRequest.Abort();
return sReturn;
}
}
catch (WebException wex)
{
// This exception will be raised if the server didn't return 200 - OK
// Try to retrieve more information about the network error
if (wex.Response != null)
{
using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
{
Console.WriteLine(
"The server returned '{0}' with the status code {1} ({2:d}).",
errorResponse.StatusDescription, errorResponse.StatusCode,
errorResponse.StatusCode);
}
}
}
}
catch (Exception excep)
{
Console.WriteLine("Exception in WebResponse. " + excep.Message + " - " + excep.StackTrace);
}
return null;
} // end HttpPost
}
}
你真的需要被調用'webRequest.Abort();'? – 2012-01-11 20:59:04