bugfix> mongodb > 投稿

いくつかの異なるチュートリアルに従って、データベースへの接続を試みました。それぞれにMongoDbに接続する独自の方法がありますが、ユーザー名とパスワードを使用して接続する方法を私に教えてくれませんでした。ここに私が扱っているものがあります:

Startup.csファイル:

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

そして、appsettings.json:

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "mongo": {
    "server": "m**go.ad.**********.com",
    "database": "a*****n-urls",
    "creds": {
      "db": "a******-urls",
      "user": "***-*****",
      "password": "*****_*****"
    }
  }

これは、ユーザーのアクセス許可を追加し、データベースにアクセスするためのpostメソッドを備えたコントローラーです。

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

そして、これはリポジトリです:

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

更新

モデル構成:

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

コネクタ:

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

回答 1 件
  • ルート属性を追加しました そして今、それは動作します。

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

    コントローラーアクションへのルーティングの詳細については、こちらをご覧ください!

あなたの答え