将mongodb连接到c#
我使用c#和asp.net mvc(visual studio 2015)。当我尝试将mongodb连接到c#时,出现以下错误:将mongodb连接到c#,c#,asp.net-mvc,mongodb,10gen-csharp-driver,C#,Asp.net Mvc,Mongodb,10gen Csharp Driver,我使用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); 这是我的代
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();
}
}
}
根据,有效的连接字符串(带有一个主机)的格式如下:
mongodb://[username:password@]主机[:端口][/[database][?选项]]
从错误消息判断,您正在使用mongodb:://localhost
。请注意,重复使用冒号,这使得此项无效。因此,您需要更正配置中的连接字符串
也就是说,在初始化MongoClient
之后,您可以直接设置MongoClientSettings
,这是为MongoClient
指定连接设置的一种方法。但您从不使用这些设置来创建客户端。如果您想使用它们,您的代码应该如下所示:
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
var client = new MongoClient(settings);
但是您不使用设置中的连接字符串。因此,您应该决定这两种指定连接设置的方法中的哪一种。非常好。我也停止使用连接字符串来连接mongodb。