■ Controller 클래스의 Json 메소드를 사용해 JSON 데이터를 받는 방법을 보여준다.
[TestServer 프로젝트]
▶ Models/TestModel.cs
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 |
using System.ComponentModel.DataAnnotations; namespace TestServer.Models { /// <summary> /// 테스트 모델 /// </summary> public class TestModel { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 성명 - Name /// <summary> /// 성명 /// </summary> [Required] [StringLength(50, MinimumLength = 3, ErrorMessage = "성명은 3자 이상 입력해 주시기 바랍니다.")] public string Name { get; set; } #endregion } } |
▶ Models/TestRepository.cs
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 |
using System.Collections.Generic; namespace TestServer.Models { /// <summary> /// 테스트 저장소 /// </summary> public class TestRepository { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 테스트 딕셔너리 /// </summary> public static Dictionary<int, TestModel> TestDictionary; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor ////////////////////////////////////////////////////////////////////////////////////////// Static #region 생성자 - TestRepository() /// <summary> /// 생성자 /// </summary> static TestRepository() { TestDictionary = new Dictionary<int, TestModel>(); TestDictionary.Add(1, new TestModel { ID = 1, Name = "홍길동" }); TestDictionary.Add(2, new TestModel { ID = 2, Name = "김철수" }); TestDictionary.Add(3, new TestModel { ID = 3, Name = "이용희" }); } #endregion } } |
▶ Controllers/TestController.cs
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 |
using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Net; using TestServer.Models; namespace TestServer.Controllers { /// <summary> /// 테스트 컨트롤러 /// </summary> [ApiController] [Route("api/[controller]")] public class TestController : Controller { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 리스트 구하기 - GetList() /// <summary> /// 리스트 구하기 /// </summary> /// <returns>리스트</returns> [HttpGet] public JsonResult GetList() { Response.StatusCode = (int)HttpStatusCode.OK; return Json(TestRepository.TestDictionary.Values.ToList()); } #endregion #region 항목 구하기 - GetItem(id) /// <summary> /// 항목 구하기 /// </summary> /// <returns>항목</returns> [HttpGet("{id:int}")] public JsonResult GetItem(int id) { if(TestRepository.TestDictionary.ContainsKey(id)) { Response.StatusCode = (int)HttpStatusCode.OK; return Json(TestRepository.TestDictionary[id]); } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(null); } } #endregion #region 항목 추가하기 - AddItem(test) /// <summary> /// 항목 추가하기 /// </summary> /// <param name="test">테스트</param> /// <returns>처리 결과</returns> [HttpPost] public JsonResult Post([FromBody]TestModel test) { if(ModelState.IsValid) { if(TestRepository.TestDictionary.ContainsKey(test.ID)) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json("FAILURE"); } TestRepository.TestDictionary.Add(test.ID, test); Response.StatusCode = (int)HttpStatusCode.Created; return Json("SUCCESS"); } Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json("FAILURE"); } #endregion } } |
[TestClient 프로젝트]
▶ Program.cs
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 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 |
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace TestClient { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> static void Main() { // 포트 5569는 서버 설정과 일치시킨다. using(HttpClient client = GetHTTPClient("http://localhost:5569/")) { List<TestModel> list; TestModel item; string status; Console.WriteLine(); Console.WriteLine("리스트를 조회합니다."); Console.WriteLine("--------------------------------------------------"); list = GetList(client).GetAwaiter().GetResult(); for(int i = 0; i < list.Count; i++) { item = list[i]; Console.WriteLine($"{item.ID}, {item.Name}"); } Console.WriteLine(); Console.WriteLine("항목을 조회합니다."); Console.WriteLine("--------------------------------------------------"); item = GetItem(client, 3).GetAwaiter().GetResult(); Console.WriteLine($"{item?.ID}, {item?.Name}"); Console.WriteLine(); Console.WriteLine("값을 추가합니다."); Console.WriteLine("--------------------------------------------------"); status = AddItem(client, new TestModel { ID = 4, Name = "백만원" }).GetAwaiter().GetResult(); Console.WriteLine(status); Console.WriteLine(); Console.WriteLine("리스트를 조회합니다."); Console.WriteLine("--------------------------------------------------"); list = GetList(client).GetAwaiter().GetResult(); for(int i = 0; i < list.Count; i++) { item = list[i]; Console.WriteLine($"{item.ID}, {item.Name}"); } Console.WriteLine("--------------------------------------------------"); Console.WriteLine("아무 키나 눌러 주시기 바랍니다."); Console.ReadKey(true); } } #endregion #region HTTP 클라이언트 구하기 - GetHTTPClient(baseAddress) /// <summary> /// HTTP 클라이언트 구하기 /// </summary> /// <param name="baseAddress">기준 주소</param> /// <returns>HTTP 클라이언트</returns> private static HttpClient GetHTTPClient(string baseAddress) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseAddress); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return client; } #endregion #region 리스트 구하기 - GetList(client) /// <summary> /// 리스트 구하기 /// </summary> /// <param name="client">클라이언트</param> /// <returns>리스트</returns> private static async Task<List<TestModel>> GetList(HttpClient client) { string url = string.Format("api/test/"); HttpResponseMessage response = await client.GetAsync(url); if(response.IsSuccessStatusCode) { List<TestModel> list = await response.Content.ReadAsAsync<List<TestModel>>(); return list; } return null; } #endregion #region 항목 구하기 - GetItem(client, id) /// <summary> /// 항목 구하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="id">ID</param> /// <returns>항목</returns> private static async Task<TestModel> GetItem(HttpClient client, int id) { string url = string.Format("api/test/{0}", id); HttpResponseMessage response = await client.GetAsync(url); if(response.IsSuccessStatusCode) { TestModel item = await response.Content.ReadAsAsync<TestModel>(); return item; } return null; } #endregion #region 항목 추가하기 - AddItem(client, item) /// <summary> /// 항목 추가하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="item">항목</param> /// <returns>처리 결과</returns> private static async Task<string> AddItem(HttpClient client, TestModel item) { string url = string.Format("api/test/"); var response = await client.PostAsJsonAsync<TestModel>(url, item); if(response.IsSuccessStatusCode) { string result = await response.Content.ReadAsAsync<string>(); return result; } return null; } #endregion } } |