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

.NET Core 3.1访问HP打印机API报SSL连接无法建立错误怎么解决

解决方案

核心问题排查

你当前代码无法触发证书校验回调的最核心原因是:你拼接的请求URL是http://前缀,HTTP协议不会走SSL/TLS握手流程,自然不会触发任何证书校验逻辑,你的回调函数永远不会被执行。

方案1:临时测试快速绕过

仅建议在本地测试阶段使用,全局放行所有证书存在安全风险:

try
{
    // 可选:如果是Linux环境下回调仍不触发,可在程序启动时添加以下配置
    // AppContext.SetSwitch("System.Net.Http.UseSocketsHttpHandler", true);
    using (var httpClientHandler = new HttpClientHandler())
    {
        // 放行所有证书校验,测试用
        httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => true;
        // 兼容老旧打印设备可能使用的低版本TLS协议
        httpClientHandler.SslProtocols = System.Security.Authentication.SslProtocols.Tls12 
                                       | System.Security.Authentication.SslProtocols.Tls11 
                                       | System.Security.Authentication.SslProtocols.Tls;
        using (var httpClient = new HttpClient(httpClientHandler))
        {
            // 核心修正:将http改为https,触发SSL校验流程
            var httpResponse = httpClient.GetAsync("https://" + protocolRelativeUrl).Result;
        }
    }
} 
catch (Exception e)
{
    // 输出完整异常栈方便后续排查
    logger.LogError(e, "调用打印机API失败");
}

方案2:生产环境安全校验方案

你已经持有打印机的官方证书,不需要全局放行所有证书,仅校验该特定证书即可规避安全风险:

  1. 先导出你提供的HP证书,计算它的SHA1/SHA256指纹
  2. 将回调逻辑修改为仅放行匹配该指纹的证书:
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => 
{
    // 替换为你的证书实际指纹值
    const string validPrinterCertThumbprint = "9A814F7D116B7D8E7C6D5B4A3F2E1D0C9B8A7F6E";
    return cert.Thumbprint.Equals(validPrinterCertThumbprint, StringComparison.OrdinalIgnoreCase);
};

其他可能的兼容问题

如果修改为HTTPS后回调仍不触发,可尝试将HttpClientHandler替换为SocketsHttpHandler实现,代码如下:

var handler = new SocketsHttpHandler
{
    SslOptions = new SslClientAuthenticationOptions
    {
        RemoteCertificateValidationCallback = (sender, cert, chain, sslPolicyErrors) => true,
        EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls11
    }
};
using var httpClient = new HttpClient(handler);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:57:03