我正在使用Asp.Net WebClient执行http post。我在代码中使用了一个try catch来捕获WebException。
try
{
using (MyWebClient wc = new MyWebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = _lender.ContentType;
wc.Timeout = 200;
return _lender.GetResult(wc.UploadString(_lender.PostUri, _lender.PostValues));
}
}
catch (WebException ex)
{
return new ServiceError(ex.Status.ToString());
}我寻找的主要例外是超时。我已经扩展了WebClient,允许我设置超时。
当我将超时设置为100ms时,如预期的那样抛出了一个异常。我可以根据示例获得webexception状态(它返回"timout"),但是我也想返回状态代码。
如果我使用ex.Response向下钻取httpwebresponse,我会得到一个null值返回,而我希望得到一个相关的状态代码。为什么我得不到HttpStatus.Request.Timeout?
发布于 2020-07-30 01:52:13
我也有同样的问题,在我寻找解决方案的时候,我意识到了一些事情。
WebExceptionStatus enum不等同于您调用的接口返回的http状态码。WebExceptionStatus错误码是WebExceptionStatus.ProtocolError,也就是7号为int。WebException.Status是否为WebExceptionStatus.ProtocolError。然后你可以从WebExceptionStatus.Response获得真正的响应并读取它的content.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/16394810
复制相似问题