简体   繁体   中英

Using C# To Connect to MongoDB on DigitalOcean Server

I have recently setup a digital ocean server and installed mongo on it. I've created ssh public and private keys to be able to login but I don't think i actually need to use ssh, or credentials for the server itself, rather than just the IP of my server and the credentials of the Mongo server.

  1. Can this be verified as correct?

2.On top of that, I'm getting an error when I'm trying to connect. I call Mongo() to connect.

The error says An exception of type 'System.ArgumentException' occurred in MongoDB.Driver.Core.dll but was not handled in user code

Additional information: 'mongodb://MongoUserName:MongoPassword@XXX.XX.XXX.XXX:27017/admin:27017' is not a valid end point.

    public static class DataSources
    {
    public static string URIString = "mongodb://"+s_Username
        +":"+s_Password+"@"+ip+":"+port+"/admin";
    public static string ip = "XXX.XX.XXX.XXX";
    public static string port = "27017";
    public static string s_Username = "MongoUsername";
    public static string s_Password = "MongoPassword";

    public static MongoCredential GetMongoCredentials()
    {
        return MongoCredential.CreateCredential("admin", s_Username, s_Password);
    }

    public static MongoClientSettings GetMongoSettings()
    {
        var settings = new MongoClientSettings
        {
            Credentials = new[] { GetMongoCredentials() },
            Server = new MongoServerAddress(URIString)
        };
        return settings;
    }
    public static MongoClient Mongo()
    {
        MongoClient mongoClient = new MongoClient(GetMongoSettings());
        return mongoClient;
    }


}

The MongoServerAddress constructor does not take the full connection string but just a server and a port like this:

new MongoServerAddress(server, port)

The MongoClient on the other hand can parse the full connection string so it should be sufficient to say:

MongoClient mongoClient = new MongoClient(URIString) and drop most of the rest of your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM