1

我得到了这段代码,它试图捕获 410 代码,但它在第一行抛出错误并且没有通过其余代码,

 HttpWebResponse response = (HttpWebResponse)request.GetResponse();

 if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Gone)
            {

有什么方法可以捕获除上述之外的 410 代码。

在下面的答案的帮助下回答代码

  try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException ex)
            {
               if (((HttpWebResponse)(ex.Response)).StatusCode == HttpStatusCode.NotFound || ((HttpWebResponse)(ex.Response)).StatusCode == HttpStatusCode.Gone)
                {
4

1 回答 1

2

这就是GetResponse方法的工作原理。当它没有得到代码时,它会抛出一个异常200

试着把你的request.GetResponse()try .. catch。抓住WebException。在catch子句中,您可以处理状态码不是时的情况200

try 
{
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
} 
catch(Exception ex)
{
    var exStatusCode = ex.Code //check the status code against this
    var exResponse = ex.Response //use your response like this
}
于 2013-06-14T12:04:50.093 回答