Я создал пример консольного приложения c # для подключения к mongodb, размещенному на компьютере CentOS на докере.
Команда, используемая для создания контейнера, приведена ниже:
запуск докера -d - имя mongodb-container -p 2020: 27017 -v / home / mongodb_data: / var / lib / mongodb / data -v / home / mongodb_log: / var / log / mongodb -v /home/mongod.conf:/etc / mongod.conf -e MONGO_INITDB_ROOT_USERNAME = mongoadmin -e MONGO_INITDB_ROOT_PASSWORD = секретный mongo
Системный IP-адрес: 172.17.103.158 Док-порт Mongodb: 2020
теперь код поступает1011 *
class users
{
[BsonId]
public ObjectId _Id { get; set; }
[BsonElement]
public string name { get; set; }
}
MongoContext Class
public class MongoContext
{
IMongoClient _client;
public readonly IMongoDatabase _database;
public MongoContext()
{
MongoCredential credential = MongoCredential.CreateCredential(ConfigurationManager.AppSettings["MongoDatabaseName"], ConfigurationManager.AppSettings["MongoUsername"], ConfigurationManager.AppSettings["MongoPassword"]);
var settings = new MongoClientSettings
{
Credential = credential,
VerifySslCertificate = false,
ConnectionMode = ConnectionMode.ReplicaSet,
ReplicaSetName = ConfigurationManager.AppSettings["MongoDatabaseName"],
UseSsl = false,
Server = new MongoServerAddress(ConfigurationManager.AppSettings["MongoHost"], Convert.ToInt32(ConfigurationManager.AppSettings["MongoPort"]))
};
_client = new MongoClient(settings);
_database = _client.GetDatabase(ConfigurationManager.AppSettings["MongoDatabaseName"]);
}
}
Web Config:
<configuration>
<appSettings>
<add key="MongoDatabaseName" value="clientdb" />
<add key="MongoUsername" value="mongoadmin" />
<add key="MongoPassword" value="secret" />
<add key="MongoPort" value="2020" />
<add key="MongoHost" value="172.17.103.158" />
</appSettings>
</configuration>
Просмотр пользователей
static List<users> ViewUsers()
{
try
{
MongoContext db = new MongoContext();
IMongoCollection<users> Table1 = db._database.GetCollection<users>("users");
return Table1.AsQueryable().ToList();
}
catch (Exception ex) { throw ex; }
}
Ошибка:
{"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 : \"172.17.103.158:2020\" }\", EndPoint: \"172.17.103.158:2020\", State: \"Disconnected\", Type: \"Unknown\", HeartbeatException: \"MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1. ---> MongoDB.Driver.MongoCommandException: Command saslStart failed: Authentication failed..\r\n at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.ProcessReply(ConnectionId connectionId, ReplyMessage`1 reply)\r\n at MongoDB.Driver.Core.WireProtocol.CommandUsingQueryMessageWireProtocol`1.<ExecuteAsync>d__14.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at MongoDB.Driver.Core.Authentication.SaslAuthenticator.<AuthenticateAsync>d__7.MoveNext()\r\n --- End of inner exception stack trace ---\r\n at MongoDB.Driver.Core.Authentication.SaslAuthenticator.<AuthenticateAsync>d__7.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at MongoDB.Driver.Core.Authentication.DefaultAuthenticator.<AuthenticateAsync>d__7.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at MongoDB.Driver.Core.Authentication.AuthenticationHelper.<AuthenticateAsync>d__1.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at MongoDB.Driver.Core.Connections.ConnectionInitializer.<InitializeConnectionAsync>d__3.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()\r\n --- End of inner exception stack trace ---\r\n at MongoDB.Driver.Core.Connections.BinaryConnection.<OpenHelperAsync>d__48.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)\r\n at MongoDB.Driver.Core.Servers.ServerMonitor.<HeartbeatAsync>d__27.MoveNext()\" }] }."}
В коротком сообщении об ошибке:
{"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 : \"172.17.103.158:2020\" }\", EndPoint: \"172.17.103.158:2020\", State: \"Disconnected\", Type: \"Unknown\", HeartbeatException: \"MongoDB.Driver.MongoConnectionException: An exception occurred while opening a connection to the server. ---> MongoDB.Driver.MongoAuthenticationException: Unable to authenticate using sasl protocol mechanism SCRAM-SHA-1. ---> MongoDB.Driver.MongoCommandException: Command saslStart failed: Authentication failed..
Я сталкиваюсь с этой проблемой, когда mongo db защищается с помощью имени пользователя и пароля, в противном случае нет.
Хотя MongoDb Compass все еще может подключиться кМонго БД в обоих случаях.
Мой вопрос : почему код C # не получаетсяподключение к mongodb при применении аутентификации к базе данных.
Решения: 1. Подключено с помощью uri: mongodb: // mongoadmin: secret@172.17.103.158: 2020 / clientdb 2. Отредактировано mongod.config => BindIp127.0.0.1, 172.17.103.17 (IP-адрес моей системы) 3. Использование механизма SCRAM-SHA-1