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

.NET使用WebClient发起GET请求如何忽略自签名SSL证书验证

解决方案

注意:跳过SSL证书验证会存在中间人攻击的安全风险,仅可在测试环境、或你100%信任目标站点的场景下使用,禁止在生产环境直接使用该配置。

方法1:全局配置跳过验证(适配你现有的WebClient代码)

WebClient的证书校验依赖全局的ServicePointManager配置,你只需要在发起请求前添加证书验证回调,直接返回true即可跳过校验:

static string Get_String(string url)
{
    // 临时设置全局证书验证回调,跳过所有校验
    ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
    string output;
    using (var wb = new WebClient())
    {
        var response = wb.DownloadString(url);
        output = response;
    }
    // 用完后重置回调,避免影响程序内其他HTTPS请求的正常证书校验
    ServicePointManager.ServerCertificateValidationCallback = null;
    return output;
}

该配置是全局生效的,如果不重置,程序后续所有的HTTPS请求都会跳过证书验证,存在安全隐患。

方法2:使用HttpClient实现局部跳过验证(更推荐)

WebClient已经是官方不推荐的过时API,.NET Core/.NET 5+ 及新项目更建议使用HttpClient,可以实现仅当前请求跳过验证,不影响全局逻辑:

static async Task<string> Get_String(string url)
{
    // 仅给当前请求的Handler配置跳过验证,不会影响其他请求
    var handler = new HttpClientHandler
    {
        ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => true
    };
    using var httpClient = new HttpClient(handler);
    return await httpClient.GetStringAsync(url);
}

内容的提问来源于stack exchange,提问作者Muhammed Özen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:42:02