You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中使用WebClient读取自定义404页面的源代码?

当然能实现!我来帮你调整下代码,既能拿到自定义404页面的源代码,又能准确判断响应的状态类型~

具体实现方案

1. 从WebException中提取404页面源代码

你当前的代码已经走到了正确的方向——404这类非2xx响应会触发WebException,我们可以从异常对象里拿到服务器返回的完整响应,进而读取页面源代码:

try 
{ 
    using (var webClient = new WebClient()) 
    { 
        webClient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0)"); 
        webClient.DownloadFile(new Uri(file.Address), file.SaveLocation); 
    } 
} 
catch (WebException e) 
{ 
    // 先确认响应对象存在,避免空引用
    if (e.Response is HttpWebResponse response)
    {
        // 判断是否是标准404状态
        if (response.StatusCode == HttpStatusCode.NotFound)
        {
            // 读取响应流里的页面源代码
            using (var streamReader = new StreamReader(response.GetResponseStream()))
            {
                string custom404Source = streamReader.ReadToEnd();
                // 这里可以对源代码做保存、分析等操作
                Console.WriteLine("自定义404页面源代码:");
                Console.WriteLine(custom404Source);
            }
        }
        // 也可以处理其他错误状态(比如403、500)
        else
        {
            Console.WriteLine($"服务器返回错误状态:{response.StatusCode} - {response.StatusDescription}");
        }
    }
}

2. 判断404的具体类型

你提到的“404类型”可以从两个维度来判断:

  • HTTP状态细分:有些服务器会返回更具体的404子状态(比如IIS的404.1、404.2),可以通过response.StatusDescription或者response.StatusCode的数值来区分;
  • 页面内容特征:如果是网站自定义的404,通常会有独特的内容(比如特定标题、品牌元素),你可以检查源代码里的关键词来确认:
// 在拿到custom404Source之后
if (custom404Source.Contains("<title>找不到页面 - 我的网站</title>"))
{
    Console.WriteLine("这是网站自定义的404页面");
}
else
{
    Console.WriteLine("这是服务器默认的404页面");
}

额外推荐:改用HttpClient(更现代的方式)

如果你的项目是.NET Core或.NET 5+,更推荐用HttpClient替代已过时的WebClient,它不需要依赖异常来处理非2xx响应,代码逻辑更清晰:

using (var httpClient = new HttpClient())
{
    httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/4.0 (compatible; MSIE 8.0)");
    try
    {
        var response = await httpClient.GetAsync(file.Address);
        
        // 不管状态码如何,先读取响应内容
        string responseContent = await response.Content.ReadAsStringAsync();
        
        if (response.StatusCode == HttpStatusCode.NotFound)
        {
            Console.WriteLine("检测到404响应,页面源代码如下:");
            Console.WriteLine(responseContent);
        }
        else
        {
            // 状态正常时保存文件
            byte[] fileBytes = await response.Content.ReadAsByteArrayAsync();
            File.WriteAllBytes(file.SaveLocation, fileBytes);
        }
    }
    catch (HttpRequestException ex)
    {
        Console.WriteLine($"请求出错:{ex.Message}");
    }
}

内容的提问来源于stack exchange,提问作者user5405648

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:24:58