2

我使用 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();
        }
    }
}
4

1 回答 1

9

根据手册,有效的连接字符串(带有一个主机)具有以下格式:

mongodb://[username:password@]host[:port][/[database][?options]]

从您的错误消息来看,您正在使用mongodb:://localhost. 注意重复的冒号,这使得这个无效。因此,您需要更正配置中的连接字符串。

话虽如此,在初始化之后直接设置MongoClient.MongoClientSettings这是为. 但是您永远不会使用这些设置来创建客户端。如果您想使用它们,您的代码应如下所示:MongoClient

MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress("localhost", 27017);
var client = new MongoClient(settings);

但是,您不使用设置中的连接字符串。因此,您应该决定要使用这两种指定连接设置的方式中的哪一种。

于 2016-03-27T12:57:34.113 回答