WebException Response属性返回null

ter*_*la7 2 .net c# error-handling httpwebresponse

我正在扫描一个有很多路径示例的网址:http://url.com/path11000.有时我会得到一个WebException但是在我的catch块中,NullReferenceException如果我不使用该行,它将引发错误
if (x.Status == WebExceptionStatus.ProtocolError && x.Response != null)

所以我的问题是:下面的代码是修复错误还是忽略它?

错误没有特定的错误路径只是随机像http://url.com/path10或任何其他链接谢谢:)

catch (WebException x)
{
    if (x.Status == WebExceptionStatus.ProtocolError && x.Response != null)
    {
        HttpWebResponse response = (HttpWebResponse)x.Response;
        if (response.StatusCode == HttpStatusCode.NotFound)
        {
           listBox3.Items.add(listBox1.Items[i].ToString());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*sey 7

根据财产文件WebException.Response

如果Internet资源中有响应,则包含来自Internet资源的错误响应的WebResponse实例; 否则,null.

所以,如果我正确地理解你的问题,那么就需要进行测试WebException.Responsenull,这意味着你的代码正确地避免了NullReferenceException,而不是"忽略"了.

希望有所帮助.