반응형

REST ( Representational State Trasnfer) 공식표준 스펙은 아닌데

원래 있던 HTTP 통신에서  재사용 하여 데이터 송수신 규칙을 만든것 => CRUD

 

 

CRUD 를 Blazor API 서버를 활용하여 작업 한것 

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using SharedData.Models;
using System.Collections.Generic;
using System.Linq;
using WebAPI.Data;

namespace WebAPI.Controllers
{
    //www.google.com 이건 전체 주소
    //www.google.com/api/ranking   이건 세부 라우팅 주소로 전체 주소에서 구분지어 들어갈 때 사용됨
    //그 다음 어떤걸 하는지 지정 할 수 있다 GET, POST, PUT...)
    //Create : POST 방식 api/ranking => body 에 실제 정보를 담는다 , 아이템 생성 요청

    //Read 시에는 보통 Get 을 사용한다
    //GET : api/ranking => 전체 아이템을 가져온다 , api/ranking/1 id가 1인 아이템을 가져온다
    //get /api/ranking  모든 id를 주세요
    //get /api/ranking/1   id 중에서 1전을 주세요 라는 요청 
    //get 은 body 에 정보를 넣지 않고 이 요청 하나로 처리 된다

    //update : put 으로 사용됨
    //PUT : api/ranking  (put은 보안 무제로 일반적인 웹에서 사용되지 않는다)
    //put 은 body 에 정보를 넣어서 요청을 보낸다

    //delete /api/ranking/1   이렇게 삭제 할 수 있는데 보안 문제로 웹에서 쓰지 않는다
    //id=1 번인 아이템 삭제 요청

    //api controller 는 c# 객체를 반환하는 것이 가능하다
    //null 반환하면 클라에서 204 Response (No Content) 를 받는다
    //String을 반호나하면 => text/plain 타입으로 반환한다
    //나머지는 json 형태로 반환한다

    //localhost:portnumber/api/ranking 이 요청이라는 얘기인데 RankingController 이것이 [controller] 부분에서 ranking 으로 변환됨
    [Route("api/[controller]")]
    [ApiController]
    public class RankingController : ControllerBase
    {
        ApplicationDbContext _context;
        public RankingController(ApplicationDbContext context)
        {
                _context = context;

        }

        //create, body 에 보낼때는 [frombody 를 넣어주면 된다]
        [HttpPost]
        public GameResult AddGameResult([FromBody] GameResult gameResult)
        {
            _context.GameResultList.Add(gameResult);
            _context.SaveChanges();
            return gameResult;
        }


        //update
        [HttpPut]
        public bool UpdateGameResult([FromBody] GameResult gameResult)
        {
            var findResult = _context.GameResultList.Where(item => item.Id == gameResult.Id).FirstOrDefault();
            if(findResult == null)
            {
                return false;
            }

            findResult.UserName = gameResult.UserName;
            findResult.Score = gameResult.Score;
            _context.SaveChanges();

            return true;
        }

        //read
        //ranking
        [HttpGet]
        public List<GameResult> GetGameResults()
        {
            List<GameResult> results = _context.GameResultList.OrderByDescending(item=> item.Score).ToList();
            return results;
        }

        //ranking/1
        [HttpGet("{id}")]
        public GameResult GetGameResult(int id)
        {
            GameResult result = _context.GameResultList.Where(item => item.Id == id).FirstOrDefault();
            return result;
        }


        //delete
        [HttpDelete("{id}")]
        public bool DeleteGameResult(int id)
        {
            var findResult = _context.GameResultList.Where(item => item.Id == id).FirstOrDefault();
            if (findResult == null)
            {
                return false;
            }
            _context.GameResultList.Remove(findResult);
            _context.SaveChanges();

            return true;
        }
    }
}

 

아래 예시는 모든 데이터를 json 으로 갖고 오는 예시이다

반응형

+ Recent posts