2. ASP.NET Core 1.x를 이용하여 Web API 만들기
ASP.NET Core로 REST API를 구성 해보려고 한다.
* REST API란
- 웹에 존재하는 자원에 대해서 고유한 URI를 부여하여 사용하는 것을 의미한다.
- 기능을 구현할 떄의 REST API 표준은 다음과 같다.
Method |
URI |
의미 |
GET |
/items |
모든 item을 조회 |
POST |
/items |
새로운 item 추가 |
GET |
/items/id |
특정 item을 조회 |
PUT |
/items/id |
특정 item을 업데이트(수정) |
DELETE |
/times/id |
특정 item을 제거 |
* ASP.NET Core에서의 기본 REST API 구성
Method |
URI |
GET |
/api/todo |
POST |
/api/todo |
GET |
/api/todo/id |
PUT |
/api/todo/id |
DELETE |
/api/todo/id |
다음 그림이 위의 REST API에 대한 디자인을 나타내고 있다.
실습환경 : visual studio 2015 sp 3
(.NET CORE 1.0 -> https://elanderson.net/2016/11/migration-from-asp-net-core-1-0-x-to-1-1/)
1. 프로젝트 생성하기
ASP.NET Core Web App (.NET Core) 선택
Web API 선택
2. Model 만들기
- Model은 Web application에서 데이터를 표현하는 오브젝트를 뜻함
- TestApi.cs라는 Model을 생성하여 다음과 같이 구성
namespace TestApi.Models |
3. Controller 만들기
- Controller 폴더에서 오른쪽 마우스 버튼 -> Add -> New item / Web API Controller Class 선택 및 추가
- 추가 시 다음과 같이 구성되어 있음
using System; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace TestApi.Controllers // GET api/values/5 // POST api/values // PUT api/values/5 // DELETE api/values/5 |
- 위에서 살펴본 다섯 가지의 REST API 표준 형식에 따라 어떻게 클래스 내에서 사용해야 하는지 보여주고 있음
1) Route : API의 URI를 결정하는 부분
- api/[controller]일때, http://hostname/api/[controller]
- [controller] controller 클래스의 앞부분이 들어감
- 즉, valuesController.cs라면 실제로 http://hostname/api/values (GET인 경우)
2) [HttpGET] Get Method
- {" "} : 조건을 보고 해당 item을 찾는 GET Method
3) [HttpPOST] POST Method
- body에서 값을 받아 기존 데이터에 추가 해준다
4) [HttpPut] Put Method
- {" "} 특정 id 값을 가진 데이터를 수정 해준다
5) [HttpDelete] Delete Method
- {" "} 특정 id 값을 가진 데이터를 삭제 해준다
예제)
using System; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace TestApi.Controllers List<Item> items = new List<Item> // GET: http://host/test/api/Item // GET http://host/test/api/Item/{id} // POST http://host/test/api/Item // PUT http://host/test/api/Item/{id} var item = items.FirstOrDefault(t => t.Id == id); item.name = updateItem.name; return item; // DELETE http://host/test/api/Item/{id} |
다음과 같이 REST API 확인툴로 볼 수 있다.
Method : DELETE http://host/test/api/Item/1