【问题标题】:connecting mongodb to c#将mongodb连接到c#
【发布时间】:2016-03-27 12:41:37
【问题描述】:

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

【问题讨论】:

    标签: c# asp.net-mvc mongodb 10gen-csharp-driver


    【解决方案1】:

    根据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);
    

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

    【讨论】:

    • 非常好。我也确实停止使用连接字符串来连接 mongodb。
    猜你喜欢
    • 2017-05-10
    • 2011-01-27
    • 2017-04-17
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    相关资源
    最近更新 更多