-4

I have tried connecting to the database following several different tutorials. Each has had their own method for connecting to MongoDb but none of them have shown me how to connect using a username and password. Here is what I am dealing with:

Startup.cs file:

  namespace ShortenUrl
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }

            public IConfiguration Configuration { get; }

            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddMvc();

                services.AddSingleton<MongoConfig>(Configuration.GetSection("mongo").Get<MongoConfig>());         // Similar To:    Configuration.GetSection("MongoConfig:Server").Value;
                services.AddSingleton<MongoConnector>();                                                          //                options.Database = 
                services.AddSingleton<Database>();                                                                //                Cofiguration.GetSection("MongoConfig:Database").Value;
                services.AddTransient<UsersRepository>();
            }

            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseBrowserLink();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }

                app.UseStaticFiles();

                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

namespace ShortenUrl.Services.Mongo
{
    public class MongoConnector
    {
        public MongoConnector(MongoConfig config)
        {
            Client = new MongoClient(new MongoClientSettings
            {
                Server = MongoServerAddress.Parse(config.Server),
                Credential = MongoCredential.CreateCredential(config.Creds.Db, config.Creds.User, config.Creds.Password),
                UseSsl = true,
                VerifySslCertificate = false,
                SslSettings = new SslSettings
                {
                    CheckCertificateRevocation = false
                }
            });

            Database = Client.GetDatabase(config.Database);
        }

        public IMongoClient Client { get; }

        public IMongoDatabase Database { get; set; }
    }
}

And appsettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "mongo": {
    "server": "****************",
    "database": "**********",
    "creds": {
      "db": "**********",
      "user": "**********",
      "password": "**********"
    }
  }

This is my Controller with a post method for adding the user permissions and gain access to the database:

public class UsersController : Controller
    {   
        private readonly UsersRepository _repo;

        public UsersController(UsersRepository repo)
        {
            _repo = repo;
        }

        [HttpPost]
        public async Task<IActionResult> Post ([FromBody] string user)
        {
            await _repo.CreateAsync(user);
            return new OkObjectResult(user);    
        }

    }
}

And this is the repository:

public class UsersRepository
{
    private readonly Database _db;

    public UsersRepository(Database db)
    {
        _db = db;
    }

    public async Task<User> CreateAsync(string username)
    {
        var user = new User { Username = username };
        await _db.Users.InsertOneAsync(user);
        return user;
    }

Update

Model Config:

namespace ShortenUrl.Services.Configs
{
    public class MongoCreds
    {
        public string Db { get; set; }
        public string User { get; set; }
        public string Password { get; set; }
    }
    public class MongoConfig
    {
        public string Server { get; set; }
        public string Database { get; set; }
        public MongoCreds Creds { get; set; }
    }
} 

Connector:

public class MongoConnector
    {
        public MongoConnector(MongoConfig config)
        {
            Client = new MongoClient(new MongoClientSettings
            {
                Server = MongoServerAddress.Parse(config.Server),
                Credential = MongoCredential.CreateCredential(config.Creds.Db, config.Creds.User, config.Creds.Password),
                UseSsl = true,
                VerifySslCertificate = false,
                SslSettings = new SslSettings
                {
                    CheckCertificateRevocation = false
                }
            });

            Database = Client.GetDatabase(config.Database);
        }

        public IMongoClient Client { get; }

        public IMongoDatabase Database { get; set; }
    }
}
JakeFromSF
  • 319
  • 2
  • 12
  • Well it might not be that helpful, but: 1) For testing purposes, try not to use ssl 2) Adding DB as a singleton is not a good idea (for testing purposes it is ok). I am not exactly sure if it is valid even for NoSQL db (https://stackoverflow.com/questions/814206/getting-db-connection-through-singleton-class) 3) I guess you should also add code from your controller "vaues" action - shouldn't that be a "values" btw? 4) Also add your config file. – suchoss May 25 '18 at 21:32
  • In Visual Studio, right-click on the start-up project, then click on Properties. Go to the *Debug* section. Where it says *Launch browser*, it should/might say *api/values*, change the URL to *ShortUrls*. Save that, and try running it again. Depending on what other controllers you have, that value may need to change. – R. Richards May 25 '18 at 21:40

1 Answers1

2

Added the route attribute and now it works.

namespace ShortenUrl.Controllers
{
    [Route("api/codes")]
    public class ShortUrlsController : Controller
    {
        private readonly ShortUrlRepository _repo;
        //private readonly IShortUrlService _service;

        public ShortUrlsController(ShortUrlRepository repo  /*IShortUrlService service*/)
        {
            _repo = repo;
            //_service = service;
        }

        [HttpGet("{id}")]
        public async Task<IActionResult> Get(string id)
        {
            var su = await _repo.GetAsync(id);

            if (su == null)
                return NotFound();

            return Ok(su);
        }

        [HttpPost]
        public async Task<IActionResult> Create([FromBody] ShortUrl su)
        {
            await _repo.CreateAsync(su);
            return Ok(su);
        }
   }
}

More information on routing to controller actions can be found HERE!

JakeFromSF
  • 319
  • 2
  • 12
  • I recently came across a really useful MongoDb tutorial that I wish I had discovered sooner so I am sharing it here: http://www.codeproject.com/Articles/1087008/Mongo-DB-Tutorial-and-Mapping-of-SQL-and-Mongo-DB – JakeFromSF Jun 05 '18 at 13:31