【问题标题】:How can I access MongoDb in Asp.Net Core with a Username and Password?如何使用用户名和密码在 Asp.Net Core 中访问 MongoDb?
【发布时间】:2018-05-25 16:27:17
【问题描述】:

我尝试按照几个不同的教程连接到数据库。每个人都有自己的连接到 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": "****************",
    "database": "**********",
    "creds": {
      "db": "**********",
      "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)出于测试目的,尽量不要使用 ssl 2)将 DB 添加为单例不是一个好主意(出于测试目的,它是可以的)。我不确定它是否对 NoSQL db (stackoverflow.com/questions/814206/…) 有效 3) 我想您还应该从控制器“vaues”操作中添加代码 - 这不应该是“值”顺便说一句吗? 4)同时添加你的配置文件。
  • 在 Visual Studio 中,右键单击启动项目,然后单击属性。转到 调试 部分。如果它说 Lau​​nch browser,它应该/可能会说 api/values,将 URL 更改为 ShortUrls。保存它,然后尝试再次运行它。根据您拥有的其他控制器,该值可能需要更改。

标签: mongodb asp.net-core


【解决方案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);
        }
   }
}

更多关于路由到控制器动作的信息可以在HERE找到!

【讨论】:

猜你喜欢
  • 2021-05-21
  • 2011-06-20
  • 2018-05-08
  • 2017-11-29
  • 1970-01-01
  • 2013-06-10
  • 2019-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多