1

我正在使用 Asp.Net WebClient 来发布 http 帖子。我尝试捕获代码以捕获 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 以允许我设置超时。

当我将超时设置为 100 毫秒时,会按预期抛出异常。我可以按照示例获取 webexception 状态(它返回“timeout”),但是我也想返回状态代码。

如果我使用 ex.Response 向下钻取以获取 httpwebresponse,当我期待相关的状态代码时,我会返回一个空值。为什么我没有得到 HttpStatus.Request.Timeout?

4

1 回答 1

0

我有同样的问题,在寻找解决方案时我意识到了一些事情。

  • WebExceptionStatus enum不等同于您调用的 API 返回的 http 状态码。相反,它是在 http 调用期间可能发生的错误的枚举。
  • WebExceptionStatus当您从 API 收到错误(400 到 599)时将返回的错误代码是WebExceptionStatus.ProtocolErrorint 形式的编号 7。
  • 当需要获取响应体或者api返回的真实http状态码时,首先需要检查 if WebException.Statusis 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.
}
于 2020-07-29T17:52:13.057 回答