Search code examples
c#asp.net-mvcmongodb10gen-csharp-driver

connecting mongodb to c#


I use c# and asp.net mvc (visual studio 2015). When I try to connect mongodb to c#,this error appears:

MongoDB.Driver.MongoConfigurationException: The connection string 'mongodb:://localhost' is not valid.

and the error source is:

var client = new MongoClient(Settings.Default.bigdataconexionstrin);

this is my code :

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

Solution

  • As per the manual, a valid connection string (with one host) is of the following format:

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

    Judging from your error message, you are using mongodb:://localhost. Note that repeated colon, which makes this invalid. So you need to correct the connection string in your configuration.

    That being said, directly after initializing the MongoClient you set up the MongoClientSettings which is an alternative way to specify the connection settings for the MongoClient. But you never use these settings to create the client. If you wanted to use them, your code should look like this:

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

    But then you don’t use the connection string from your settings. So you should decide which of these two ways of specifying the connection settings you want to use.