我有一个WCF服务,它每分钟运行到外部API的频繁(1000+)出站连接。
我的代码经常抛出以下异常,但并不总是显示是一个ReceiveFailure状态属性为WebException的WebException
发出出站请求的代码如下:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(paramBuilder.ToString());
request.ServicePoint.ConnectionLeaseTimeout = 0;
request.Method = "GET";
request.Timeout = 33000; //33 Second Timeout Is By Design
Stream stream = default(Stream);
HttpWebResponse response = default(HttpWebResponse);
try
{
response = (HttpWebResponse) request.GetResponse();
stream = response.GetResponseStream();
reader = new StreamReader(stream,Encoding.UTF8);
string str = reader.ReadToEnd();
return str;
}
catch (WebException exception)
{
//Handle WebException
}
catch (Exception exception)
{
//Handle Exception
}
finally
{
if (reader != null)
reader.Dispose();
if (response != null)
response.Close();
if (stream != null)
stream.Dispose();
}异常堆栈跟踪显示异常是由GetResponse()引起的。
如果我偶尔收到一个WebException -ReceiveFailure,会发生什么事情呢?
对于这种状态,我已经引用了MSDN文档,但这对我没有帮助。
发布于 2013-07-23 20:28:58
在黑暗中射击..。
在等待响应时,有一个特殊的条件:如果系统时钟是由Windows时间服务自动设置的,或者是手动设置的,您可能会遇到一些不可预测的结果。
如果您在HTTPS上发送请求,可能您正面临一个错误抛出的常规超时( ReceiveFailure )。
有关更多信息,请查看本文:http://support.microsoft.com/kb/2007873
发布于 2020-07-29 17:54:07
我有一个相关的问题,在我寻找解决方案的时候,我意识到一些事情。
WebExceptionStatus enum不等同于您调用的API返回的http状态代码。相反,它是一个可能的错误的枚举,可能发生在一个http调用。WebExceptionStatus错误代码是WebExceptionStatus.ProtocolError,也就是编号7的int。WebException.Status是否为WebExceptionStatus.ProtocolError。然后,您可以从WebExceptionStatus.Response获得真正的响应并阅读其内容。WebException.Status是否是WebExceptionStatus.Timeout这就是一个例子:
try
{
...
}
catch (WebException webException)
{
if (webException.Status == WebExceptionStatus.ProtocolError)
{
var httpResponse = (HttpWebResponse)webException.Response;
var responseText = "";
using (var content = new StreamReader(httpResponse.GetResponseStream()))
{
responseText = content.ReadToEnd(); // Get response body as text
}
int statusCode = (int)httpResponse.StatusCode; // Get the status code
}
else if (webException.Status == WebExceptionStatus.ProtocolError)
{
// Timeout handled by your code. You do not have a response here.
}
// Handle other webException.Status errors. You do not have a response here.
}https://stackoverflow.com/questions/17819881
复制相似问题