Connect to remote MongoDB instance from ASP.NET

2019-04-10 02:21发布

I'm having some trouble nutting out why I'm unable to connect to a new database I've created at MongoHQ.

I want to include the correct connection string in my Web.config file and have my Mongo object refer to that for the database connection.

The connection strings (edited, obviously) are:

Public Access

mongo flame.mongohq.com:27065/dunedin -u {username} -p {password}

AWS Internal Access

mongo flame.local.mongohq.com:27065/dunedin -u {username} -p {password}

Obviously, I've included my correct username in password in place of the placeholders in the braces.

My code is:

string connection = ConfigurationManager.ConnectionStrings["DBMongo"].ConnectionString;
var mongo = new Mongo(connection);

mongo.Connect();

However, as soon as I try to instantiate that Mongo object, I get a format exception saying

Invalid connection string on:

What is that connection string supposed to look like for remotely-hosted MongoDB instances?

EDIT:

The Connection String entry in Web.Config is

<add name="DBMongo" connectionString="mongo flame.mongohq.com:27065/dunedin -u ausername -p apassword"/>

4条回答
\"骚年 ilove
2楼-- · 2019-04-10 02:45

The connection string for MongoDB is formatted as a URI, details can be found here. Below is the basic format and some examples:

mongodb://[username:password@]host1[:port1][/[database][?options]]

mongodb://127.0.0.1 

mongodb://127.0.0.1/mydatabase

mongodb://mongosrv.com:10230/mydatabase

mongodb://myadmin:secretpass@mongosrv.com:10230/mydatabase

// Or in your case it would be 

mongodb://ausername:apassword@flame.mongohq.com:27065/dunedin

You can also use MongoUrlBuilder and MongoUrl to construct or parse the connection string programatticaly. Though a bit wordy, I believe the recommended usage goes like this

var mongoUrl = new MongoUrl(settings.ConnectionString);
var mongoClient = new MongoClient(mongoUrl);
var mongoServer = mongoClient.GetServer();
var mongoDatabase = mongoServer.GetDatabase(mongoUrl.DatabaseName); 
查看更多
霸刀☆藐视天下
3楼-- · 2019-04-10 02:53

How does your connection string placed in Web.config look like? Exception you get indicates that it's invalid. Clarify it using MongoDB documentation.

查看更多
做自己的国王
4楼-- · 2019-04-10 03:01

You are obviously using mongodb-csharp. What you are using most definately is not a valid connection string. You can ask your question at the group http://groups.google.com/group/mongodb-csharp or look at the docs and code here. There is even a connection string builder so you don't need to know the exact syntax.

查看更多
等我变得足够好
5楼-- · 2019-04-10 03:10

In the mongo shell, type show users. Then use the hashed password this displays for your password in the connection string.

查看更多
登录 后发表回答