■ CRUD 구현 WEB API 애플리케이션을 만드는 방법을 보여준다.
[TestServer 프로젝트]
▶ Models/ValueRepository.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 |
using System.Collections.Generic; namespace TestServer { /// <summary> /// 값 저장소 /// </summary> public static class ValueRepository { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Public #region Field /// <summary> /// 값 리스트 /// </summary> public static List<string> ValueList = new List<string>() { "Console", "WinForm", "WPF" }; #endregion } } |
▶ Models/TransferItem.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 |
namespace TestServer.Models { /// <summary> /// 전송 항목 /// </summary> public class TransferItem { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 상태 - Status /// <summary> /// 상태 /// </summary> public string Status { get; set; } #endregion #region 컨텐트 - Content /// <summary> /// 컨텐트 /// </summary> public string Content { get; set; } #endregion } } |
▶ Controllers/ValueController.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 |
using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using TestServer.Models; namespace TestServer.Controllers { /// <summary> /// 값 컨트롤러 /// </summary> [ApiController] [Route("api/[controller]")] public class ValueController : ControllerBase { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 값 추가하기 - AddValue(value) /// <summary> /// 값 추가하기 /// </summary> /// <param name="value">값</param> /// <returns>전송 항목</returns> [HttpPost] public TransferItem AddValue([FromBody]string value) { TransferItem item = new TransferItem(); if(ValueRepository.ValueList.Contains(value)) { item.Status = "FAILURE"; item.Content = null; return item; } else { ValueRepository.ValueList.Add(value); item.Status = "OK"; item.Content = null; return item; } } #endregion #region 값 수정하기 - UpdateValue(index, value) /// <summary> /// 값 수정하기 /// </summary> /// <param name="index">인덱스</param> /// <param name="value">값</param> /// <returns>전송 항목</returns> [HttpPut("{index:int}")] public TransferItem UpdateValue(int index, [FromBody]string value) { TransferItem item = new TransferItem(); if(index < 0 || index >= ValueRepository.ValueList.Count) { item.Status = "FAILURE"; item.Content = null; return item; } ValueRepository.ValueList[index] = value; item.Status = "OK"; item.Content = null; return item; } #endregion #region 값 삭제하기 - DeleteValue(index) /// <summary> /// 값 삭제하기 /// </summary> /// <param name="index">인덱스</param> /// <returns>전송 항목</returns> [HttpDelete("{index:int}")] public TransferItem DeleteValue(int index) { TransferItem item = new TransferItem(); if(index < 0 || index >= ValueRepository.ValueList.Count) { item.Status = "FAILURE"; item.Content = null; return item; } ValueRepository.ValueList.RemoveAt(index); item.Status = "OK"; item.Content = null; return item; } #endregion #region 값 리스트 구하기 - GetValueList() /// <summary> /// 값 리스트 구하기 /// </summary> /// <returns>전송 항목</returns> [HttpGet] public TransferItem GetValueList() { TransferItem item = new TransferItem(); item.Status = "OK"; item.Content = JsonConvert.SerializeObject(ValueRepository.ValueList); return item; } #endregion #region 값 구하기 - GetValue(index) /// <summary> /// 값 구하기 /// </summary> /// <param name="index">인덱스</param> /// <returns>전송 항목</returns> [HttpGet("{index:int}")] public TransferItem GetValue(int index) { TransferItem item = new TransferItem(); if(index < 0 || index >= ValueRepository.ValueList.Count) { item.Status = "FAILURE"; item.Content = null; return item; } item.Status = "OK"; item.Content = JsonConvert.SerializeObject(ValueRepository.ValueList[index]); return item; } #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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 |
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Newtonsoft.Json; 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<string> valueList; Console.WriteLine(); Console.WriteLine("값 리스트를 조회합니다."); Console.WriteLine("--------------------------------------------------"); valueList = GetValueList(client).GetAwaiter().GetResult(); for(int i = 0; i < valueList.Count; i++) { Console.WriteLine(valueList[i]); } Console.WriteLine(); Console.WriteLine("값을 조회합니다."); Console.WriteLine("--------------------------------------------------"); string value = GetValue(client, 0).GetAwaiter().GetResult(); Console.WriteLine(value); Console.WriteLine(); Console.WriteLine("값을 추가합니다."); Console.WriteLine("--------------------------------------------------"); bool status = AddValue(client, "JAVA").GetAwaiter().GetResult(); Console.WriteLine(status); Console.WriteLine(); Console.WriteLine("값 리스트를 조회합니다."); Console.WriteLine("--------------------------------------------------"); valueList = GetValueList(client).GetAwaiter().GetResult(); for(int i = 0; i < valueList.Count; i++) { Console.WriteLine(valueList[i]); } Console.WriteLine(); Console.WriteLine("값을 수정합니다."); Console.WriteLine("--------------------------------------------------"); status = UpdateValue(client, 3, "JAVA2").GetAwaiter().GetResult(); Console.WriteLine(status); Console.WriteLine(); Console.WriteLine("값 리스트를 조회합니다."); Console.WriteLine("--------------------------------------------------"); valueList = GetValueList(client).GetAwaiter().GetResult(); for(int i = 0; i < valueList.Count; i++) { Console.WriteLine(valueList[i]); } Console.WriteLine(); Console.WriteLine("값을 삭제합니다."); Console.WriteLine("--------------------------------------------------"); status = DeleteValue(client, 3).GetAwaiter().GetResult(); Console.WriteLine(status); Console.WriteLine(); Console.WriteLine("값 리스트를 조회합니다."); Console.WriteLine("--------------------------------------------------"); valueList = GetValueList(client).GetAwaiter().GetResult(); for(int i = 0; i < valueList.Count; i++) { Console.WriteLine(valueList[i]); } 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 값 리스트 구하기 - GetValueList(client) /// <summary> /// 값 리스트 구하기 /// </summary> /// <param name="client">클라이언트</param> /// <returns>값 리스트</returns> private static async Task<List<string>> GetValueList(HttpClient client) { string url = string.Format("api/value/"); HttpResponseMessage response = await client.GetAsync(url); if(response.IsSuccessStatusCode) { TransferItem item = await response.Content.ReadAsAsync<TransferItem>(); if(item.Status.Equals("OK")) { return JsonConvert.DeserializeObject<List<string>>(item.Content); } } return null; } #endregion #region 값 구하기 - GetValue(client, index) /// <summary> /// 값 구하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="index">ID</param> /// <returns>값</returns> private static async Task<string> GetValue(HttpClient client, int index) { string url = string.Format("api/value/{0}", index); HttpResponseMessage response = await client.GetAsync(url); if(response.IsSuccessStatusCode) { TransferItem item = await response.Content.ReadAsAsync<TransferItem>(); if(item.Status.Equals("OK")) { return JsonConvert.DeserializeObject<string>(item.Content); } } return null; } #endregion #region 값 추가하기 - AddValue(client, value) /// <summary> /// 값 추가하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="value">값</param> /// <returns>처리 결과</returns> private static async Task<bool> AddValue(HttpClient client, string value) { string url = string.Format("api/value/"); var response = await client.PostAsJsonAsync<string>(url, value); if(response.IsSuccessStatusCode) { TransferItem item = await response.Content.ReadAsAsync<TransferItem>(); if(item.Status.Equals("OK")) { return true; } } return false; } #endregion #region 값 수정하기 - UpdateValue(client, index, value) /// <summary> /// 값 수정하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="index">인덱스</param> /// <param name="value">값</param> /// <returns>처리 결과</returns> private static async Task<bool> UpdateValue(HttpClient client, int index, string value) { string url = string.Format("api/value/{0}", index); var response = await client.PutAsJsonAsync(url, value); if(response.IsSuccessStatusCode) { TransferItem item = await response.Content.ReadAsAsync<TransferItem>(); if(item.Status.Equals("OK")) { return true; } } return false; } #endregion #region 값 삭제하기 - DeleteValue(client, index) /// <summary> /// 값 삭제하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="index">인덱스</param> /// <returns>처리 결과</returns> private static async Task<bool> DeleteValue(HttpClient client, int index) { string url = string.Format("api/value/{0}", index); var response = await client.DeleteAsync(url); if(response.IsSuccessStatusCode) { TransferItem item = await response.Content.ReadAsAsync<TransferItem>(); if(item.Status.Equals("OK")) { return true; } } return false; } #endregion } } |