将 mongodb 连接到 C#
connecting mongodb to c#
我使用 c# 和 asp.net mvc(visual studio 2015)。当我尝试将 mongodb 连接到 c# 时,出现此错误:
MongoDB.Driver.MongoConfigurationException: The connection string 'mongodb:://localhost' is not valid.
错误来源是:
var client = new MongoClient(Settings.Default.bigdataconexionstrin);
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using WebApplication5.Properties;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
namespace WebApplication5.Controllers
{
[Authorize]
public class HomeController : Controller
{
public IMongoDatabase db1;
public HomeController()
{
var client = new MongoClient(Settings.Default.bigdataconexionstrin);
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
this.db1 = client.GetDatabase(Settings.Default.db);
}
public ActionResult Index()
{
return View();
}
}
}
根据 the manual,有效的连接字符串(与一台主机)格式如下:
mongodb://[username:password@]host[:port][/[database][?options]]
从您的错误消息来看,您正在使用 mongodb:://localhost
。注意重复的冒号,这使得这个无效。因此,您需要更正配置中的连接字符串。
也就是说,在初始化 MongoClient
之后,您直接设置了 MongoClientSettings
,这是一个 alternative way 来指定 MongoClient
的连接设置。但是您永远不会使用这些设置来创建客户端。如果你想使用它们,你的代码应该是这样的:
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
var client = new MongoClient(settings);
但是您没有使用设置中的连接字符串。因此,您应该决定使用这两种指定连接设置的方法中的哪一种。
我使用 c# 和 asp.net mvc(visual studio 2015)。当我尝试将 mongodb 连接到 c# 时,出现此错误:
MongoDB.Driver.MongoConfigurationException: The connection string 'mongodb:://localhost' is not valid.
错误来源是:
var client = new MongoClient(Settings.Default.bigdataconexionstrin);
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using WebApplication5.Properties;
using MongoDB.Driver;
using MongoDB.Driver.Linq;
namespace WebApplication5.Controllers
{
[Authorize]
public class HomeController : Controller
{
public IMongoDatabase db1;
public HomeController()
{
var client = new MongoClient(Settings.Default.bigdataconexionstrin);
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
this.db1 = client.GetDatabase(Settings.Default.db);
}
public ActionResult Index()
{
return View();
}
}
}
根据 the manual,有效的连接字符串(与一台主机)格式如下:
mongodb://[username:password@]host[:port][/[database][?options]]
从您的错误消息来看,您正在使用 mongodb:://localhost
。注意重复的冒号,这使得这个无效。因此,您需要更正配置中的连接字符串。
也就是说,在初始化 MongoClient
之后,您直接设置了 MongoClientSettings
,这是一个 alternative way 来指定 MongoClient
的连接设置。但是您永远不会使用这些设置来创建客户端。如果你想使用它们,你的代码应该是这样的:
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
var client = new MongoClient(settings);
但是您没有使用设置中的连接字符串。因此,您应该决定使用这两种指定连接设置的方法中的哪一种。