what make ex.Response returns null

本文关键字:returns null Response ex make what | 更新日期: 2023-09-27 18:29:30

我正在扫描一个具有多个路径的url,例如:http://url.com/path11000。有时我会得到一个WebException,但在我的catch块中,如果我不使用行,它会抛出一个NullReferenceException错误

if (x.Status == WebExceptionStatus.ProtocolError && x.Response != null)

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

还有一件事,有时没有错误,有时有错误,但大多数时候都会出错,但如果使用下面的代码,一切都会很好。

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());
        }
    }
}

what make ex.Response returns null

下面的代码是修复错误还是忽略它

可以检查响应是否为null。这是正确的做法,因为响应可能为null。

在什么情况下,响应可以为空,这就是MSDN所说的

如果可以从Internet资源获得响应,则WebResponse包含来自互联网资源的错误响应的实例;否则为null。