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

WebClient调用DownloadString返回(302)Found错误如何修复

错误原因

你遇到的302 Found是HTTP重定向响应,触发原因主要有两个:

  1. 所用的Pastebin链接不是原始内容链接,普通分享页面会触发302跳转至实际内容页;
  2. WebClient未配置自动跟随重定向,或者缺少必要的User-Agent请求头被Pastebin拦截跳转。

可行修复方案

  • 方案1:修改现有WebClient逻辑,补全配置
    1. 先把你用的Pastebin链接替换为raw原始内容链接,格式为https://pastebin.com/raw/你的pasteID,不要用普通分享页链接
    2. 给WebClient添加请求头、开启自动重定向,同时修复原代码中文件名不匹配、重复实例化的问题,修改后代码如下:
// 自定义支持重定向配置的WebClient
public class CustomWebClient : WebClient
{
    public int MaxRedirects { get; set; } = 10;
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
        request.AllowAutoRedirect = true;
        request.MaximumAutomaticRedirections = MaxRedirects;
        // 添加模拟浏览器的UA,避免Pastebin拦截
        request.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36";
        return request;
    }
}

// 业务逻辑代码
string SourceDir = @"./";
string SourceZip = @"./FILE";
using (var client = new CustomWebClient())
{
    // 这里替换为你的Pastebin raw原始链接
    string downloadUrl = client.DownloadString("https://pastebin.com/raw/你的PasteID");
    // 清理链接首尾的空白、换行符避免请求失败
    client.DownloadFile(downloadUrl.Trim(), SourceZip);
}
ZipFile.ExtractToDirectory(SourceZip, SourceDir);
System.IO.File.Delete(SourceZip);
Process.Start(@"./FILE");
  • 方案2:改用官方更推荐的HttpClient实现(WebClient已在.NET Core/.NET 5+中被标记为过时)
    代码示例:
// HttpClient全局只需要实例化一次即可,不要每次请求都新建
private static readonly HttpClient _httpClient = new HttpClient(new HttpClientHandler()
{
    AllowAutoRedirect = true,
    MaxAutomaticRedirections = 10
});

// 初始化请求头
static void InitHttpClient()
{
    _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36");
}

// 业务逻辑
async Task DownloadAndRun()
{
    string SourceDir = @"./";
    string SourceZip = @"./FILE";
    InitHttpClient();
    // 替换为Pastebin raw链接
    string downloadUrl = await _httpClient.GetStringAsync("https://pastebin.com/raw/你的PasteID");
    var fileBytes = await _httpClient.GetByteArrayAsync(downloadUrl.Trim());
    await System.IO.File.WriteAllBytesAsync(SourceZip, fileBytes);
    ZipFile.ExtractToDirectory(SourceZip, SourceDir);
    System.IO.File.Delete(SourceZip);
    Process.Start(@"./FILE");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 21:27:01