我想使用配置文件(App.Config)指定MongoClient连接字符串。有内置的方法可以执行此操作吗?还是可以只使用ConnectionStringsSection?
最佳答案
设定档
<connectionStrings>
<add name="MongoSessionServices" connectionString="mongodb:/localhost:27017" />
<add name="DefaultMongoConnection" connectionString="mongodb://localhost:27017" />
</connectionStrings>
<appSettings>
<add key="MongoDbName" value="your_database" />
</appSettings>
获取Mongo服务器
public static MongoServer GetConnection()
{
MongoClient mc = new MongoClient(string.IsNullOrEmpty(ConnectionText) ? System.Configuration.ConfigurationManager.ConnectionStrings["DefaultMongoConnection"].ConnectionString : ConnectionText);
return mc.GetServer();
}
获取Mongo数据库
public static MongoDatabase GetDatabase(string database = "")
{
if (string.IsNullOrEmpty(database))
{
return GetConnection().GetDatabase(string.IsNullOrEmpty(DatabaseText) ? System.Configuration.ConfigurationManager.AppSettings.Get("MongoDbName") : DatabaseText);
}
else
{
return GetConnection().GetDatabase(database);
}
}