프로그래밍/C#

[C#] ASP.Net Core를 이용하여 Rest Api 서버만들기

ss-pro 2020. 9. 7. 01:07
반응형

이번시간에는 ASP.NET Core를 사용하여 restful api서버를 만들어보겠습니다. MSDN에 나온설명대로 그대로 따라해보도록 하겠습니다. 

MSDN 링크
docs.microsoft.com/ko-kr/aspnet/core/tutorials/first-web-api?view=aspnetcore-3.1&tabs=visual-studio

Entity Framework 사용법
www.csharpstudy.com/Data/EF-basics.aspx

 

자습서: ASP.NET Core를 사용하여 웹 API 만들기

ASP.NET Core를 사용하여 웹 API를 빌드하는 방법을 알아봅니다.

docs.microsoft.com

1. GET API테스트 
먼저 ASP.NET Core 웹 어플리케이션항목을 선택한다음 API 항목을 선택하여 프로젝트를 만들기를 클릭합니다. 

만들기를 완료하면 WetherForecastController.cs파일이 자동생성이되며 프로그램을 빌드하면 Get메서드를 호출하여 브라우저에 WeatherForecast 멤버정보가 Json형태로 나오는것을 확인할수 있습니다. 

그럼 이제 Weatherforecast를 참고해서 TodoItem모델에대하여 GET,POST,PUT,PATCH,DELETE 명령을 제공하는 API를 만들어 보도록 하겠습니다. 


2. GET,PUT,POST,DELETE API 테스트
도구->NuGet패키지관리자->솔루션NuGet패킷관리 항목을 선택하면 아래와 같이 솔루션항목이 나오면  Microsoft.Entity.FrameworkCore.SqlServer, Microsoft.EntityFrameworkCore.InMemory  두개솔루션을 받아서 설치하도록 하겠습니다. 


TodoItem.cs 모델 클래스를 아래와 같이 생성합니다. 
해당모델에 대하여 CRUD작업을 진행하는 API를 만들어 보도록 하겠습니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
 
namespace WebApplication3
{
    public class TodoItem
    {
        public int Id { get; set; }
 
        public string Name { get; set; }
 
        public bool IsComplete { get; set; }
 
    }
}
 

TodoContext 클래스를 만들어 보겠습니다. DbContext 클래스를 상속받아서 생성합니다. 그리고 TodoItem모델을 DbSet으로 받을수 있게 TodoItems멤버변수를 만듭니다. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
 
using Microsoft.EntityFrameworkCore;
 
namespace WebApplication3
{
    public class TodoContext : DbContext
    {
        public TodoContext(DbContextOptions<TodoContext> options)
            : base(options)
        {
        }
 
        public DbSet<TodoItem> TodoItems { get; set; }
    }
}
 

StartUp클래스 ConfigureServices항목에 아래와 같이 소스코드를 추가해 넣습니다.  
services.AddDbContext<TodoContext>(opt => opt.UseInMemoryDatabase("TodoList"));
UseInMemoryDatabase를 사용해서 테스트용도로 사용하도록 하겠습니다.

스캐폴드 항목추가 
스캐폴드란 무엇일까요?  사전을 찾아보면 학습자에게 적절한 인지적 도움과 안내를 제공하여 학습을 촉진시키는 전략이라고 합니다. 이 의미가 무엇인지는 아래 예제를 따라해보면 알수 있습니다. 스캐폴드 항목을 이용하여 컨트롤러를 추가하게되면 자동으로 GET,PUT,POST,DELETE 샘플소스코드가 생성됩니다. 
컨트롤러 폴더에서 -> 추가 -> 컨트롤러를 클릭합니다. Entity Framework를 사용하여 동작이 포함된 API컨트롤러 항목을 선택합니다. 

모델클래스, 데이터컨텍스트 클래스를 선택한다음 추가버튼을 클릭합니다

스캐폴딩으로 생성된 TodoItemsController소스코드입니다. GET,PUT,POST,DELETE API소스코드가 자동으로 생성되는것을 확인 할수 있습니다. 이제 필요한 부분을 더 추가하거나 보완하고 필요로그를 더 기록하면 되겠죠. MSDN을 그대로 따라해봤습니다.  

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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using WebApplication3;
 
namespace WebApplication3.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TodoItemsController : ControllerBase
    {
        private readonly TodoContext _context;
 
        public TodoItemsController(TodoContext context)
        {
            _context = context;
        }
 
        // GET: api/TodoItems
        [HttpGet]
        public async Task<ActionResult<IEnumerable<TodoItem>>> GetTodoItems()
        {
            return await _context.TodoItems.ToListAsync();
        }
 
        // GET: api/TodoItems/5
        [HttpGet("{id}")]
        public async Task<ActionResult<TodoItem>> GetTodoItem(int id)
        {
            var todoItem = await _context.TodoItems.FindAsync(id);
 
            if (todoItem == null)
            {
                return NotFound();
            }
 
            return todoItem;
        }
 
        // PUT: api/TodoItems/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutTodoItem(int id, TodoItem todoItem)
        {
            if (id != todoItem.Id)
            {
                return BadRequest();
            }
 
            _context.Entry(todoItem).State = EntityState.Modified;
 
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!TodoItemExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
 
            return NoContent();
        }
 
        // POST: api/TodoItems
        // To protect from overposting attacks, enable the specific properties you want to bind to, for
        // more details, see https://go.microsoft.com/fwlink/?linkid=2123754.
        [HttpPost]
        public async Task<ActionResult<TodoItem>> PostTodoItem(TodoItem todoItem)
        {
            _context.TodoItems.Add(todoItem);
            await _context.SaveChangesAsync();
 
            return CreatedAtAction("GetTodoItem"new { id = todoItem.Id }, todoItem);
        }
 
        // DELETE: api/TodoItems/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<TodoItem>> DeleteTodoItem(int id)
        {
            var todoItem = await _context.TodoItems.FindAsync(id);
            if (todoItem == null)
            {
                return NotFound();
            }
 
            _context.TodoItems.Remove(todoItem);
            await _context.SaveChangesAsync();
 
            return todoItem;
        }
 
        private bool TodoItemExists(int id)
        {
            return _context.TodoItems.Any(e => e.Id == id);
        }
    }
}
 
cs


POSTMAN 프로그램을 사용한 테스트 
API정상적으로 만들어졌는지 테스트해보도록 하겠습니다. 테스트는 포스트맨 프로그램을 사용하도록 하겠습니다. 
다운로드링크: www.postman.com 에서 프로그램을 다운 받습니다. 

GET : https://localhost:44358/api/TodoItems


POST명령어를 사용하여 Item을 등록해보겠습니다. 
Header항목에 Key값은 Content-Type로 선택하고 Value application/json으로 입력합니다. 
Body항목에 raw로 선택한다음 등록하는 데이터를 json형태로 입력합니다. 
Body항목에 아래와 같이 입력후 Send버튼을 클릭하면 Request에 아래와 같이 응답을 주는것을 확인할수 있습니다. 
{
    "name""walk dog",
    "isComplete"true
}

Raw에 데이터를 입력후 왼쪽상단의 Code항목을 누르면 프로그램 언어별로 간략하게 소스코드를 제공하니 프로그램 개발시 참고하시기 바랍니다. 

이제 GET명령을 POSTMAN 또는 브라우저에서  조회해보면 POST명령으로 등록한 자료가 조회되는 부분을 확인하실수 있습니다. Get Url :  https://localhost:44358/api/TodoItems 

웹 서비스 API를 만드는게 이제 버튼 클릭 몇번으로 기본적인 CRUD기능을 손쉽게 만들수 있습니다.프레임워크를 얼마나 잘 활용하느냐에 따라서 개발 생산성 및 안정성이 많이 향상될것 같습니다.  

반응형