■ 스캐폴딩 기능을 사용해 WEB API 앱을 만드는 방법을 보여준다.
▶ Models/TodoModel.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
namespace TestProject.Models { /// <summary> /// 할일 모델 /// </summary> public class TodoModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public long ID { get; set; } #endregion #region 제목 - Name /// <summary> /// 제목 /// </summary> public string Name { get; set; } #endregion #region 완료 여부 - IsComplete /// <summary> /// 완료 여부 /// </summary> public bool IsComplete { get; set; } #endregion } } |
▶ Data/DatabaseContext.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
using Microsoft.EntityFrameworkCore; using TestProject.Models; namespace TestProject.Data { /// <summary> /// 데이터베이스 컨텍스트 /// </summary> public class DatabaseContext : DbContext { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 할일 - Todo /// <summary> /// 할일 /// </summary> public DbSet<TodoModel> Todo { get; set; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - DatabaseContext(options) /// <summary> /// 생성자 /// </summary> /// <param name="options">옵션</param> public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options) { } #endregion } } |
▶ Startup.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using TestProject.Data; namespace TestProject { /// <summary> /// 시작 /// </summary> public class Startup { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 구성 - Configuration /// <summary> /// 구성 /// </summary> public IConfiguration Configuration { get; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - Startup(configuration) /// <summary> /// 생성자 /// </summary> /// <param name="configuration">구성</param> public Startup(IConfiguration configuration) { Configuration = configuration; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 서비스 컬렉션 구성하기 - ConfigureServices(services) /// <summary> /// 서비스 컬렉션 구성하기 /// </summary> /// <param name="services">서비스 컬렉션</param> public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DatabaseContext>(options => options.UseInMemoryDatabase("TodoList")); services.AddControllers(); } #endregion #region 구성하기 - Configure(app, environment) /// <summary> /// 구성하기 /// </summary> /// <param name="app">애플리케이션 빌더</param> /// <param name="environment">웹 호스트 환경</param> public void Configure(IApplicationBuilder app, IWebHostEnvironment environment) { if(environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints ( endpointRouterBuilder => { endpointRouterBuilder.MapControllers(); } ); } #endregion } } |
▶ Controllers/TodoController.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TestProject.Data; using TestProject.Models; namespace TestProject.Controllers { /// <summary> /// 할일 컨트롤러 /// </summary> [ApiController] [Route("api/[controller]")] public class TodoController : ControllerBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 데이터베이스 컨텍스트 /// </summary> private readonly DatabaseContext context; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Public #region 생성자 - TodoController(context) /// <summary> /// 생성자 /// </summary> /// <param name="context">컨텍스트</param> public TodoController(DatabaseContext context) { this.context = context; } #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region GET 처리하기 - Get() /// <summary> /// GET 처리하기 /// </summary> /// <returns>액션 결과 태스크</returns> [HttpGet] public async Task<ActionResult<IEnumerable<TodoModel>>> Get() { return await this.context.Todo.ToListAsync(); } #endregion #region GET 처리하기 - Get(id) /// <summary> /// GET 처리하기 /// </summary> /// <param name="id">ID</param> /// <returns>액션 결과 태스크</returns> [HttpGet("{id}")] public async Task<ActionResult<TodoModel>> Get(long id) { TodoModel todo = await this.context.Todo.FindAsync(id); if(todo == null) { return NotFound(); } return todo; } #endregion #region POST 처리하기 - Post(todo) /// <summary> /// POST 처리하기 /// </summary> /// <param name="todo">할일</param> /// <returns>액션 결과 태스크</returns> [HttpPost] public async Task<ActionResult<TodoModel>> Post(TodoModel todo) { this.context.Todo.Add(todo); await this.context.SaveChangesAsync(); return CreatedAtAction("Get", new { id = todo.ID }, todo); } #endregion #region PUT 처리하기 - Put(id, todo) /// <summary> /// PUT 처리하기 /// </summary> /// <param name="id">ID</param> /// <param name="todo">할일</param> /// <returns>액션 결과 태스크</returns> [HttpPut("{id}")] public async Task<IActionResult> Put(long id, TodoModel todo) { if(id != todo.ID) { return BadRequest(); } this.context.Entry(todo).State = EntityState.Modified; try { await this.context.SaveChangesAsync(); } catch(DbUpdateConcurrencyException) { if(!TodoExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } #endregion #region DELETE 처리하기 - Delete(id) /// <summary> /// DELETE 처리하기 /// </summary> /// <param name="id">ID</param> /// <returns>액션 결과 태스크</returns> [HttpDelete("{id}")] public async Task<ActionResult<TodoModel>> Delete(long id) { TodoModel todo = await this.context.Todo.FindAsync(id); if(todo == null) { return NotFound(); } this.context.Todo.Remove(todo); await this.context.SaveChangesAsync(); return todo; } #endregion ////////////////////////////////////////////////////////////////////////////////////////// Private #region 할일 존재 여부 구하기 - TodoExists(id) /// <summary> /// 할일 존재 여부 구하기 /// </summary> /// <param name="id"></param> /// <returns>할일 존재 여부</returns> private bool TodoExists(long id) { return this.context.Todo.Any(e => e.ID == id); } #endregion } } |