首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WebException超时与HttpWebResponse超时

WebException超时与HttpWebResponse超时
EN

Stack Overflow用户
提问于 2013-05-06 16:26:49
回答 1查看 63关注 0票数 1

我正在使用Asp.Net WebClient执行http post。我在代码中使用了一个try catch来捕获WebException。

代码语言:javascript
复制
        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?

EN

回答 1

Stack Overflow用户

发布于 2020-07-30 01:52:13

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

  • WebExceptionStatus enum不等同于您调用的接口返回的http状态码。
  • 当你的接口收到错误(400到599)时,返回的WebExceptionStatus错误码是WebExceptionStatus.ProtocolError,也就是7号为int。
  • 当你需要获取接口返回的响应体或真正的http状态码时,首先需要检查WebException.Status是否为WebExceptionStatus.ProtocolError。然后你可以从WebExceptionStatus.Response获得真正的响应并读取它的content.
  • Sometimes,超时是由调用者(也就是你的代码)处理的,所以在这种情况下你没有响应。因此,您可以查看WebException.Status是否为WebExceptionStatus.Timeout

这是一个示例:

代码语言:javascript
复制
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.
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16394810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档