代码之家  ›  专栏  ›  技术社区  ›  Gilsham

System.Net.WebException异常HTTP状态代码

  •  135
  • Gilsham  · 技术社区  · 16 年前

    有没有一种简单的方法可以从 System.Net.WebException ?

    6 回复  |  直到 10 年前
        1
  •  257
  •   LukeH    16 年前

    也许是这样的。。。

    try
    {
        // ...
    }
    catch (WebException ex)
    {
        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            var response = ex.Response as HttpWebResponse;
            if (response != null)
            {
                Console.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
            }
            else
            {
                // no http status code available
            }
        }
        else
        {
            // no http status code available
        }
    }
    
        2
  •  29
  •   Kiquenet user385990    8 年前

    通过使用 null-conditional operator ( ?. )您可以通过一行代码获取HTTP状态代码:

     HttpStatusCode? status = (ex.Response as HttpWebResponse)?.StatusCode;
    

    status 将包含 HttpStatusCode . 当出现更一般的故障时,比如网络错误,没有发送HTTP状态码 将为空。那样的话你可以检查一下 ex.Status 为了得到 WebExceptionStatus .

    null-coalescing operator ( ??

    string status = (ex.Response as HttpWebResponse)?.StatusCode.ToString()
        ?? ex.Status.ToString();
    

    如果由于404 HTTP状态码引发异常,字符串将包含“NotFound”。另一方面,如果服务器脱机,字符串将包含“ConnectFailure”等等。

    (对于任何想知道如何获取HTTP子状态的人来说 代码。这是不可能的。这是一个微软IIS的概念,只是

        3
  •  10
  •   miniyou    9 年前

    (我确实意识到这个问题由来已久,但它是谷歌最热门的问题之一。)

    通常情况下,您希望知道响应代码处于异常处理中。从C#7开始,只有在异常与谓词匹配时,才可以使用模式匹配来实际输入catch子句:

    catch (WebException ex) when (ex.Response is HttpWebResponse response)
    {
         doSomething(response.StatusCode)
    }
    

    WebException 实际上是另一个内在的例外(我们只对 404 ):

    catch (StorageException ex) when (ex.InnerException is WebException wex && wex.Response is HttpWebResponse r && r.StatusCode == HttpStatusCode.NotFound)
    

    最后:请注意,当catch子句与您的条件不匹配时,不需要在其中重新抛出异常,因为我们不会在上面的解决方案中首先输入该子句。

        4
  •  9
  •   sharptooth    9 年前

    try
    {
        ...
    }
    catch (System.Net.WebException exc)
    {
        var webResponse = exc.Response as System.Net.HttpWebResponse;
        if (webResponse != null && 
            webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
        {
            MessageBox.Show("401");
        }
        else
            throw;
    }
    
        5
  •  5
  •   Sergey    8 年前

    您可以尝试使用此代码从WebException获取HTTP状态代码。它在Silverlight中也可以工作,因为SL没有WebExceptionStatus.ProtocolError错误定义。

    HttpStatusCode GetHttpStatusCode(WebException we)
    {
        if (we.Response is HttpWebResponse)
        {
            HttpWebResponse response = (HttpWebResponse)we.Response;
            return response.StatusCode;
        }
        return null;
    }
    
        6
  •  1
  •   JaredPar    16 年前

    我不确定是否有,但如果有这样一个财产,它不会被认为是可靠的。A WebException