목표 : ASP.NET Core 웹 API 컨트롤러와 .NET 및 C#을 사용한 플랫폼 간 RESTful 서비스 작성 살펴보기~

<aside> 🍗 따라하기~

ASP.NET Core 컨트롤러를 사용하여 웹 API 만들기 - Training

</aside>

환경 세팅

  1. .NET 8.0 버전 다운로드

  2. VS Code와 Extension 설치


웹 API 컨트롤러

WeatherController 코드 분석

using Microsoft.AspNetCore.Mvc;

namespace ContosoPizza.Controllers; // Web API 컨트롤러 및 작업 메서드 구성에 사용할 수 있는 attribute를 제공해주는 네임스페이스

[ApiController] // attribute -> 넌 이제부터 ApiController다!
[Route("[controller]")]
public class WeatherForecastController : ControllerBase // Controller아니고 ControllerBase 상속받기
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")] 
    // Get 메서드에 대한 attribute -> 이게 HTTP Get 요청을 IEnumerable<WeatherForecast> Get() 메서드로 라우팅해줌
    public IEnumerable<WeatherForecast> Get()
    {
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
            TemperatureC = Random.Shared.Next(-20, 55),
            Summary = Summaries[Random.Shared.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

데이터 저장소 추가

피자 모델 만들기

  1. Models 폴더 생성 → MVC 아키텍처에서 따온 이름

    mkdir Models
    
  2. Pizza.cs 파일 생성

    스크린샷 2024-02-07 오전 11.16.20.png