This issue has me stumped. It's happened three times in the last 12 months on our production server and causes major issues when it does. Any help would be appreciated.
We have a .NET Windows Service that sends HTTP requests to a third-party server. "Something" happens and the next 2-3 requests fail with server error 503, subsequent requests get timeout exceptions. Sounds like a server issue right? However if I type the request URL into a browser it returns response.
The issue is resolved by restarting the .NET service, which now makes me think it is a client problem, but I can't think of how. Is the underlying TCP connection to the server being reused or cached? Is there a way I can force .NET to re-create the connection?
开发者_开发问答Below is the web request code.
public string GetResponseFromServer( string requestXML, string serverUrl, int Timeout )
{
System.Net.WebRequest req = System.Net.WebRequest.Create( serverUrl );
req.Method = "POST";
req.Timeout = Timeout;
byte[] requestBodyBytes = System.Text.Encoding.UTF8.GetBytes( requestXML );
req.ContentLength = requestBodyBytes.Length;
Stream newStream = req.GetRequestStream();
newStream.Write( requestBodyBytes, 0, requestBodyBytes.Length );
newStream.Close();
System.Net.WebResponse response = req.GetResponse();
StreamReader reader = new StreamReader( response.GetResponseStream() );
return reader.ReadToEnd();
}
The errors may be related to resource leaks. Neither response
, reader
nor the stream returned by response.GetResponseStream()
are being disposed. Wrap those resources in using
statements to make sure they all get disposed of properly:
using (Stream newStream = req.GetRequestStream())
{
newStream.Write( requestBodyBytes, 0, requestBodyBytes.Length );
}
using (System.Net.WebResponse response = req.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (StreamReader reader = new StreamReader( responseStream ))
{
return reader.ReadToEnd();
}
}
}
精彩评论