※あくまで一例です。
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"MongoDBSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "MessageDatabase-RestfulAPI"
},
"AllowedHosts": "*"
}
Context/MongoDBContext
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using RESTfulAPI_MessageSystemAPI.Models;
namespace RESTfulAPI_MessageSystemAPI.Context
{
public class MongoDBContext
{
public readonly IMongoDatabase _database;
public MongoDBContext(IConfiguration configuration)
{
var connectionString = configuration.GetSection("MongoDBSettings:ConnectionString").Value;
var databaseName = configuration.GetSection("MongoDBSettings:DatabaseName").Value;
var client = new MongoClient(connectionString);
_database = client.GetDatabase(databaseName);
}
public IMongoCollection<UserModels> Users => _database.GetCollection<UserModels>("Users");
public IMongoCollection<MessageModels> Messages => _database.GetCollection<MessageModels>("Messages");
}
}
program.cs
using RESTfulAPI_MessageSystemAPI.Context;
using MongoDB.Driver;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddSingleton<MongoDBContext>();
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();