logo MSJO.kr

REST API .NET 6.0, MongoDB

2022-01-23
MsJ
   

Intro to MongoDB with C#1에 이어 이번 주제는 MongoDB와 함께 ASP.NET Core 6 REST API2를 구현하는 예제(Sample)이다. 이전과 마찬가지로 Nuget에서 MongoDB.Driver 패키지를 추가한다.

appsettings.json
{
  "UserInfoDatabaseSetting": {
    "UserInfoCollectionName": "UserInfo",
    "ConnectionString": "mongodb://<ID>:<Password>@localhost:27017/?serverSelectionTimeoutMS=5000&connectTimeoutMS=10000&authSource=testdb&authMechanism=SCRAM-SHA-256",
    "DatabaseName": "testdb"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}  
UserInfoDatabaseSetting.cs
// interface
namespace UserInfoManagement.Models
{
    public interface IUserInfoDatabaseSetting
    {
        string UserInfoCollectionName { get; set; }
        string ConnectionString { get; set; }
        string DatabaseName { get; set; }
    }
}

// class model
namespace UserInfoManagement.Models
{
    public class UserInfoDatabaseSetting : IUserInfoDatabaseSetting
    {
        public string UserInfoCollectionName { get; set; } = string.Empty;
        public string ConnectionString { get; set; } = string.Empty;
        public string DatabaseName { get; set; } = string.Empty;
    }
}
MongoDB, testdb.UserInfo
{ 
    "_id" : ObjectId("61eaa77a9102f8d5ae5f01c4"), 
    "UserId" : "1111", 
    "UserPwd" : "1111", 
    "UserName" : "홍길동"
}
{ 
    "_id" : ObjectId("61eaa976318b8b74ca7fc524"), 
    "UserId" : "2222", 
    "UserPwd" : "2222", 
    "UserName" : "가나닭"
}
UserInfo.cs
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace UserInfoManagement.Models
{
    public class UserInfo
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; } = string.Empty;

        [BsonElement("UserId")]
        public string UserId { get; set; } = string.Empty;

        [BsonElement("UserPwd")]
        public string UserPwd { get; set; } = string.Empty;

        [BsonElement("UserName")]
        public string UserName { get; set; } = string.Empty;
    }
}
UserInfoService.cs
// interface
using UserInfoManagement.Models;

namespace UserInfoManagement.Services
{
    public interface IUserInfoService
    {
        Task<List<UserInfo>> GetList();

        UserInfo Get(string id);

        UserInfo Create(UserInfo userInfo);

        void Update(string id, UserInfo userInfo);

        void Remove(string id);
    }
}

// class(Service)
using MongoDB.Driver;
using UserInfoManagement.Models;

namespace UserInfoManagement.Services
{
    public class UserInfoService : IUserInfoService
    {
        private readonly IMongoCollection<UserInfo> _userInfo;

        public UserInfoService(IUserInfoDatabaseSetting setting, IMongoClient mongoClient)
        {
            var database = mongoClient.GetDatabase(setting.DatabaseName);
            _userInfo = database.GetCollection<UserInfo>(setting.UserInfoCollectionName);
        }

        public UserInfo Create(UserInfo userInfo)
        {
            _userInfo.InsertOne(userInfo);
            return userInfo;
        }

        public async Task<List<UserInfo>> GetList()
        {
            var cursor = await _userInfo.FindAsync(u => true);
            return cursor.ToList();
        }

        public UserInfo Get(string userId)
        {
            return _userInfo.Find(u => u.UserId == userId).FirstOrDefault();
        }

        public void Remove(string userId)
        {
            _userInfo.DeleteOne(u => u.UserId == userId);
        }

        public void Update(string userId, UserInfo userInfo)
        {
            _userInfo.ReplaceOne(u => u.UserId == userId, userInfo);
        }
    }
}
UserInfoController.cs
using Microsoft.AspNetCore.Mvc;
using UserInfoManagement.Models;
using UserInfoManagement.Services;

namespace UserInfoManagement.Controllers
{
    [Route("api")]
    [ApiController]
    public class UserInfoController : ControllerBase
    {
        private readonly IUserInfoService userInfoService;

        public UserInfoController(IUserInfoService userInfoService)
        {
            this.userInfoService = userInfoService;
        }

        [HttpPost("GetUserInfoList")]
        public async Task<ActionResult<List<UserInfo>>> GetUserInfoList()
        {
            return await userInfoService.GetList();
        }

        [HttpPost("GetUserInfo")]
        public ActionResult<UserInfo> GetUserInfo([FromBody] UserInfo userInfo)
        {
            var _userInfo = userInfoService.Get(userInfo.UserId);
            if (_userInfo == null)
            {
                return new UserInfo { UserId = userInfo.UserId + " : 사용자 없음" };
            }
            return _userInfo;
        }
    }
}
Program.cs
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using UserInfoManagement.Models;
using UserInfoManagement.Services;

var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<UserInfoDatabaseSetting>(builder.Configuration.GetSection(nameof(UserInfoDatabaseSetting)));
builder.Services.AddSingleton<IUserInfoDatabaseSetting>(s => s.GetRequiredService<IOptions<UserInfoDatabaseSetting>>().Value);
builder.Services.AddSingleton<IMongoClient>(s => new MongoClient(builder.Configuration.GetValue<string>("UserInfoDatabaseSetting:ConnectionString")));
builder.Services.AddScoped<IUserInfoService, UserInfoService>();

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Reference
  1. msjo.kr, “Intro to MongoDB with C#”
  2. kudvenkat, “ASP.NET Core 6 REST API Tutorial, MongoDB Database”

Prεv(Θld)   Nεxt(Nεw)
Content RustLang.kr
Search     RSS Feed     BY-NC-ND