.Net配置MongoClientSettings连接MongoDB超时异常求助
问题场景
我使用.Net连接MongoDB时,通过手动配置MongoClientSettings的方式出现超时异常,但直接用连接字符串实例化MongoClient就能正常连接。
异常代码(手动配置Settings)
var clientSettings = new MongoClientSettings() { ConnectTimeout = TimeSpan.FromSeconds(30), SocketTimeout = TimeSpan.FromSeconds(30), WaitQueueTimeout = TimeSpan.FromSeconds(30), Server = new MongoServerAddress("host", portnumber) }; var dbClient = new MongoClient(clientSettings); var _mongoDb = dbClient.GetDatabase(db); var mongoCollection = _mongoDb.GetCollection<T>(collection); // 查询时触发超时 var retVal = await mongoCollection.Find(filter).ToListAsync(); return retVal;
异常信息
One or more errors occurred. (A timeout occured after 30000ms selecting a server using CompositeServerSelector{ Selectors = MongoDB.Driver.MongoClient+AreSessionsSupportedServerSelector, LatencyLimitingServerSelector{ AllowedLatencyRange = 00:00:00.0150000 } }. Client view of cluster state is { ClusterId : "1", ConnectionMode : "Automatic", Type : "Unknown", State : "Disconnected", Servers : [{ ServerId: "{ ClusterId : 1, EndPoint : "Unspecified/xxxx-mongoapi.documents.azure.com:10255" }", EndPoint: "Unspecified/xxxx-mongoapi.documents.azure.com:10255", State: "Disconnected", Type: "Unknown", LastUpdateTimestamp: "2022-09-16T11:18:00.8150834Z" }] }.)
正常连接方式(使用连接字符串)
var dbClient = new MongoClient(connectionString);
问题原因及解决方法
问题出在手动配置MongoClientSettings时,遗漏了Azure Cosmos DB MongoDB API要求的强制配置项,而连接字符串中已经包含这些参数,驱动会自动解析并应用。
关键缺失配置项及修复:
- SSL强制启用:Azure MongoDB API要求必须通过SSL连接,手动配置时需显式开启
- 认证信息:需要添加数据库认证的用户名、密码
- 可选:ServerApi版本:部分新驱动版本需要指定MongoDB API版本
修改后的完整配置代码
var clientSettings = new MongoClientSettings() { ConnectTimeout = TimeSpan.FromSeconds(30), SocketTimeout = TimeSpan.FromSeconds(30), WaitQueueTimeout = TimeSpan.FromSeconds(30), Server = new MongoServerAddress("xxxx-mongoapi.documents.azure.com", 10255), // 启用SSL,Azure环境强制要求 SslSettings = new SslSettings { Enabled = true }, // 添加认证信息,替换为你的实际数据库名、用户名、密码 Credential = MongoCredential.CreateCredential( databaseName: "your-database-name", username: "your-account-username", password: "your-account-password" ), // 针对MongoDB驱动2.15+版本,指定ServerApi版本(可选但推荐) ServerApi = new ServerApi(ServerApiVersion.V1) }; var dbClient = new MongoClient(clientSettings); var _mongoDb = dbClient.GetDatabase(db); var mongoCollection = _mongoDb.GetCollection<T>(collection); var retVal = await mongoCollection.Find(filter).ToListAsync(); return retVal;
补充说明
连接字符串通常包含以下核心参数(对应手动配置项):
ssl=true→ 对应SslSettings.Enabled = trueusername=xxx&password=xxx→ 对应Credential配置serverApi=1→ 对应ServerApi配置
手动配置时必须覆盖这些参数才能和连接字符串达到相同的连接效果。
内容的提问来源于stack exchange,提问作者Simon Price

