1. 웹 API 개요
2. HTTP 프로토콜
3. 웹 API 개발
새로운 프로젝트 생성 시 ASP.NET CORE 웹 API 템플릿을 선택하고 컨트롤러를 추가합니다. 컨트롤러 코드 예시는 다음과 같습니다:
[Route("api/[controller]/[action]")]
public class ApiController : ControllerBase
{
[HttpGet]
public int GetSum(int a, int b)
{
return a + b;
}
[HttpPost]
public string PostSum([FromBody] RequestModel a)
{
return a.Value0;
}
public class RequestModel
{
public string Value0 { get; set; }
public string Value1 { get; set; }
}
}
4. 웹 API 배포
1) IIS에 웹 API 배포 방법은 참고 자료 4를 참조하세요.
2) OWIN을 사용한 HTTP 서버 구축 방법은 참고 자료 1을 참조하세요.
구현 단계:
- 패키지 관리자 콘솔에서 다음 패키지를 설치: WebApi.Owin, Microsoft.Owin.Host.HttpListener, Microsoft.Owin.Hosting, Owin
- Startup 클래스 생성 (OWIN 구성용)
- QueryController 클래스 생성 (GET/POST/PUT/DELETE 요청 처리)
- 시작 메서드 추가
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
namespace OwinTest
{
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
}
public class DataController : ApiController
{
[HttpGet]
public string GetData(string id)
{
return id;
}
[HttpPost]
public string PostData([FromBody] RequestParams dp)
{
return dp.TValue0;
}
[HttpPut]
public void UpdateData(int id, string value)
{
}
[HttpDelete]
public void DeleteData(int id)
{
}
public class RequestParams
{
public string TValue0 { get; set; }
public string TValue1 { get; set; }
}
}
static void Main(string[] args)
{
string baseAddress = "http://localhost:9000/";
var disposeTemp = WebApp.Start<Startup>(url: baseAddress);
Console.ReadLine();
}
5. MySQL 데이터베이스 연동 (Entity Framework Core 기반)
1) 패키지 설치: Microsoft.EntityFrameworkCore, MySql.EntityFrameworkCore, Swashbuckle.AspNetCore
2) 데이터베이스 테이블 구조 생성
3) C#에서 엔티티 클래스 정의 및 DbContext 상속 클래스 작성
4) 컨트롤러 생성