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

使用C#通过带TLS的连接字符串连接MongoDB失败求助

MongoDB TLS连接失败(.NET客户端)

问题背景

已确认证书有效,通过Mongo Shell命令和MongoDB Compass均可正常连接启用TLS的MongoDB,但使用.NET客户端通过连接字符串连接时失败,服务端返回SSL握手失败错误,提示未收到客户端证书。

有效连接方式

  1. Mongo Shell命令
mongo --tls --tlsCAFile D:\DEV\ca-valid.pem --tlsCertificateKeyFile D:\DEV\mongo-valid.pem --host localhost --port 27017 --username admin --password test --authenticationDatabase admin
  1. MongoDB Compass连接字符串
mongodb://localhost:27017/?tls=true&tlsCertificateKeyFile=D%3A%5CDEV%5Cmongo-valid.pem&tlsCAFile=D%3A%5CDEV%5Cca-valid.pem

.NET客户端错误信息

{"t":{"$date":"2024-05-23T15:12:11.684+01:00"},"s":"I",  "c":"NETWORK",  "id":22988,   "ctx":"conn11603","msg":"Error receiving request from client. Ending connection from remote","attr":{"error":{"code":141,"codeName":"SSLHandshakeFailed","errmsg":"no SSL certificate provided by peer; connection rejected"},"remote":"127.0.0.1:52931","connectionId":11603}}

.NET使用的连接字符串

mongodb://admin:test@localhost:27017/?tls=true&tlsCertificateKeyFile=D%3A%5CDEV%5Cmongo-valid.pem&tlsCAFile=D%3A%5CDEV%5Cca-valid.pem&authSource=admin

MongoDB服务端配置

port: 27017
bindIp: 127.0.0.1
tls:
 mode: requireTLS
 certificateKeyFile: D:\DEV\mongo-valid.pem
 CAFile: D:\DEV\ca-valid.pem

解决方法尝试

  • 调整连接字符串路径格式
    替换URL编码的路径为正斜杠或双反斜杠格式,避免解析异常:

    mongodb://admin:test@localhost:27017/?tls=true&tlsCertificateKeyFile=D:/DEV/mongo-valid.pem&tlsCAFile=D:/DEV/ca-valid.pem&authSource=admin
    

    或

    mongodb://admin:test@localhost:27017/?tls=true&tlsCertificateKeyFile=D:\\DEV\\mongo-valid.pem&tlsCAFile=D:\\DEV\\ca-valid.pem&authSource=admin
    
  • 通过代码显式配置SSL参数
    绕过连接字符串解析,直接在代码中配置证书和TLS选项:

    var settings = MongoClientSettings.FromConnectionString("mongodb://admin:test@localhost:27017/?tls=true&authSource=admin");
    settings.SslSettings = new SslSettings
    {
        ClientCertificates = new[] { new X509Certificate2("D:\\DEV\\mongo-valid.pem") },
        CaCertificates = new[] { new X509Certificate2("D:\\DEV\\ca-valid.pem") },
        EnabledSslProtocols = System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13
    };
    var client = new MongoClient(settings);
    

    若pem文件带密码,需在加载证书时传入密码参数。

  • 更新.NET驱动版本
    确保使用最新稳定版的MongoDB.Driver NuGet包,旧版本可能存在TLS参数解析或证书处理的bug。

  • 检查证书文件权限
    确认运行.NET程序的用户对D:\DEV目录下的pem文件有读取权限,避免因权限不足导致证书加载失败。

  • 显式指定TLS协议版本
    在连接字符串中添加协议版本参数,匹配服务端支持的TLS版本:

    mongodb://admin:test@localhost:27017/?tls=true&tlsCertificateKeyFile=D%3A%5CDEV%5Cmongo-valid.pem&tlsCAFile=D%3A%5CDEV%5Cca-valid.pem&authSource=admin&tlsProtocol=TLS12
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 13:39:50