public MongoDbContext(IConfiguration configuration) { // Đăng ký conventionPack RegisterConventionPack(); var mongoSettings = configuration.GetSection("ConnectionStrings").Get <MongoDBSettings>(); MongoClientSettings settings = new MongoClientSettings(); settings.Server = new MongoServerAddress(mongoSettings.Host, mongoSettings.Port); settings.UseTls = mongoSettings.UserTls; settings.SslSettings = new SslSettings(); settings.SslSettings.EnabledSslProtocols = SslProtocols.Tls12; MongoIdentity identity = new MongoInternalIdentity(mongoSettings.AuthDbName, mongoSettings.UserName); MongoIdentityEvidence evidence = new PasswordEvidence(mongoSettings.Password); settings.Credential = new MongoCredential(mongoSettings.AuthMechanism, identity, evidence); MongoClient client = new MongoClient(settings); _database = client.GetDatabase(mongoSettings.DbName); //var mongoUrl = new MongoUrl(connectionString); //_client = new MongoClient(mongoUrl); //_database = _client.GetDatabase(mongoUrl.DatabaseName); }
public static MongoClient getClient() { string username = Environment.GetEnvironmentVariable("MONGODB_USERNAME"); string password = Environment.GetEnvironmentVariable("MONGODB_PASSWORD"); MongoClientSettings settings = new MongoClientSettings(); if (username != null && password != null) { string mongoDbAuthMechanism = "SCRAM-SHA-1"; MongoInternalIdentity internalIdentity = new MongoInternalIdentity("admin", username); PasswordEvidence passwordEvidence = new PasswordEvidence(password); MongoCredential mongoCredential = new MongoCredential(mongoDbAuthMechanism, internalIdentity, passwordEvidence); // comment this line below if your mongo doesn't run on secured mode settings.Credential = mongoCredential; Console.WriteLine("Got creds for Mongodb"); } else { Console.WriteLine("No creds for Mongodb"); } String mongoHost = "mongo"; MongoServerAddress address = new MongoServerAddress(mongoHost); settings.Server = address; return(new MongoClient(settings)); }