Я попытался подключиться к базе данных, следуя нескольким различным учебникам.У каждого был свой метод подключения к 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; }
}
}