■ WEB API 2 셀프 호스팅을 사용하는 방법을 보여준다.
[TestServer 프로젝트 실행 결과]
[TestClient 프로젝트 실행 결과]
[TestCommon 프로젝트]
▶ Product.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 |
namespace TestCommon { /// <summary> /// 제품 /// </summary> public class Product { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region ID - ID /// <summary> /// ID /// </summary> public int ID { get; set; } #endregion #region 제품명 - Name /// <summary> /// 제품명 /// </summary> public string Name { get; set; } #endregion #region 카테고리 - Category /// <summary> /// 카테고리 /// </summary> public string Category { get; set; } #endregion #region 가격 - Price /// <summary> /// 가격 /// </summary> public decimal Price { get; set; } #endregion } } |
[TestServer 프로젝트]
▶ ProductsController.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 |
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using TestCommon; namespace TestServer { /// <summary> /// 제품들 컨트롤러 /// </summary> public class ProductsController : ApiController { //////////////////////////////////////////////////////////////////////////////////////////////////// Field ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region Field /// <summary> /// 제품 리스트 /// </summary> private static List<Product> _productList = new List<Product> { new Product { ID = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { ID = 2, Name = "Yo-yo" , Category = "Toys" , Price = 3.75M }, new Product { ID = 3, Name = "Hammer" , Category = "Hardware" , Price = 16.99M } }; #endregion //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Public #region 제품 추가하기 - AddProduct(source) /// <summary> /// 제품 추가하기 /// </summary> /// <param name="source">소스 제품</param> /// <returns>처리 결과</returns> [HttpPost] public IHttpActionResult AddProduct(Product source) { _productList.Add(source); return Ok("SUCCESS"); } #endregion #region 제품 수정하기 - UpdateProduct(source) /// <summary> /// 제품 수정하기 /// </summary> /// <param name="source">소스 제품</param> /// <returns>처리 결과</returns> [HttpPut] public IHttpActionResult UpdateProduct(Product source) { for(int i = 0; i < _productList.Count; i++) { Product product = _productList[i]; if(product.ID == source.ID) { _productList[i].Name = source.Name; _productList[i].Category = source.Category; _productList[i].Price = source.Price; return Ok("SUCCESS"); } } return Ok("NOUPDATE"); } #endregion #region 제품 삭제하기 - DeleteProduct(id) /// <summary> /// 제품 삭제하기 /// </summary> /// <param name="id">ID</param> /// <returns>처리 결과</returns> [HttpDelete] public IHttpActionResult DeleteProduct(int id) { for(int i = 0; i < _productList.Count; i++) { if(_productList[i].ID == id) { _productList.RemoveAt(i); return Ok("SUCCESS"); } } return Ok("NODELETE"); } #endregion #region 모든 제품 리스트 구하기 - GetAllProductList() /// <summary> /// 모든 제품 리스트 구하기 /// </summary> /// <returns>모든 제품 리스트</returns> public List<Product> GetAllProductList() { return _productList; } #endregion #region 카테고리로 제품 리스트 구하기 - GetProductListByCategory(category) /// <summary> /// 카테고리로 제품 리스트 구하기 /// </summary> /// <param name="category">카테고리</param> /// <returns>제품 리스트</returns> public List<Product> GetProductListByCategory(string category) { return _productList.Where(p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)).ToList(); } #endregion #region 제품 구하기 - GetProduct(id) /// <summary> /// 제품 구하기 /// </summary> /// <param name="id">ID</param> /// <returns>제품</returns> public IHttpActionResult GetProduct(int id) { Product product = _productList.FirstOrDefault(p => p.ID == id); if(product == null) { return NotFound(); } return Ok(product); } #endregion } } |
▶ 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 |
using System; using System.Diagnostics; using System.Web.Http; using System.Web.Http.SelfHost; namespace TestServer { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { string serverURL = string.Format("http://127.0.0.1:{0}", 8080); string bindingAddress = string.Format("http://+:{0}/" , 8080); HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration(serverURL); configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional }); try { AddHTTPURLReservation(bindingAddress); using(HttpSelfHostServer server = new HttpSelfHostServer(configuration)) { server.OpenAsync().Wait(); Console.WriteLine("서버를 중단하기 위해서 아무 키나 눌러 주시기 바랍니다."); Console.ReadKey(true); } } finally { DeleteHTTLURLReservation(bindingAddress); } } #endregion #region HTTP URL 예약 추가하기 - AddHTTPURLReservation(bindingAddress) /// <summary> /// HTTP URL 예약 추가하기 /// </summary> /// <param name="bindingAddress">바인딩 주소</param> private static void AddHTTPURLReservation(string bindingAddress) { try { string argument = string.Format("http add urlacl url={0} user=everyone listen=yes", bindingAddress); ProcessStartInfo processStartInfo = new ProcessStartInfo("netsh", argument); processStartInfo.Verb = "runas"; processStartInfo.CreateNoWindow = true; processStartInfo.WindowStyle = ProcessWindowStyle.Hidden; processStartInfo.UseShellExecute = true; Process.Start(processStartInfo).WaitForExit(); } catch { } } #endregion #region HTTP URL 예약 삭제하기 - DeleteHTTLURLReservation(bindingAddress) /// <summary> /// HTTP URL 예약 삭제하기 /// </summary> /// <param name="bindingAddress">바인딩 주소</param> private static void DeleteHTTLURLReservation(string bindingAddress) { try { string argument = string.Format("http delete urlacl url={0}", bindingAddress); ProcessStartInfo processStartInfo = new ProcessStartInfo("netsh", argument); processStartInfo.Verb = "runas"; processStartInfo.CreateNoWindow = true; processStartInfo.WindowStyle = ProcessWindowStyle.Hidden; processStartInfo.UseShellExecute = true; Process.Start(processStartInfo).WaitForExit(); } catch { } } #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 293 294 295 |
using System; using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using TestCommon; namespace TestClient { /// <summary> /// 프로그램 /// </summary> class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #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 제품 추가하기 - AddProduct(client, product) /// <summary> /// 제품 추가하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="product">제품</param> /// <returns>결과 코드 태스크</returns> private static async Task<string> AddProduct(HttpClient client, Product product) { string url = string.Format("api/products/"); var response = await client.PostAsJsonAsync<Product>(url, product); if(response.IsSuccessStatusCode) { string resultCode = await response.Content.ReadAsAsync<string>(); return resultCode; } return null; } #endregion #region 제품 수정하기 - UpdateProduct(client, product) /// <summary> /// 제품 수정하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="product">제품</param> /// <returns>결과 코드 태스크</returns> private static async Task<string> UpdateProduct(HttpClient client, Product product) { string url = string.Format("api/products/"); var response = await client.PutAsJsonAsync(url, product); if(response.IsSuccessStatusCode) { string resultCode = await response.Content.ReadAsAsync<string>(); return resultCode; } return null; } #endregion #region 제품 삭제하기 - DeleteProduct(client, id) /// <summary> /// 제품 삭제하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="id">ID</param> /// <returns>결과 코드</returns> private static async Task<string> DeleteProduct(HttpClient client, int id) { string url = string.Format("api/products/{0}", id); var response = await client.DeleteAsync(url); if(response.IsSuccessStatusCode) { string resultCode = await response.Content.ReadAsAsync<string>(); return resultCode; } return null; } #endregion #region 모든 제품 리스트 구하기 - GetAllProductList(client) /// <summary> /// 모든 제품 리스트 구하기 /// </summary> /// <param name="client">클라이언트</param> /// <returns>제품 리스트</returns> private static async Task<List<Product>> GetAllProductList(HttpClient client) { string url = string.Format("api/products/"); HttpResponseMessage response = await client.GetAsync(url); if(response.IsSuccessStatusCode) { List<Product> productList = await response.Content.ReadAsAsync<List<Product>>(); return productList; } return null; } #endregion #region 카테고리로 제품 리스트 구하기 - GetProductListByCategory(client, category) /// <summary> /// 카테고리로 제품 리스트 구하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="category">카테고리</param> /// <returns>제품 리스트</returns> private static async Task<List<Product>> GetProductListByCategory(HttpClient client, string category) { string url = string.Format("api/products/?category={0}", category); HttpResponseMessage response = await client.GetAsync(url); if(response.IsSuccessStatusCode) { List<Product> productList = await response.Content.ReadAsAsync<List<Product>>(); return productList; } return null; } #endregion #region ID로 제품 구하기 - GetProductByID(client, id) /// <summary> /// ID로 제품 구하기 /// </summary> /// <param name="client">클라이언트</param> /// <param name="id">ID</param> /// <returns>제품 태스크</returns> private static async Task<Product> GetProductByID(HttpClient client, int id) { string url = string.Format("api/products/{0}", id); HttpResponseMessage response = await client.GetAsync(url); if(response.IsSuccessStatusCode) { Product product = await response.Content.ReadAsAsync<Product>(); return product; } return null; } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { List<Product> productList = null; Product product = null; using(HttpClient client = GetHTTPClient("http://localhost:8080/")) { Console.WriteLine("제품을 추가합니다."); Console.WriteLine("--------------------------------------------------"); Product source = new Product(); source.ID = 4; source.Name = "제품1"; source.Price = 10m; source.Category = "그룹1"; AddProduct(client, source).GetAwaiter().GetResult(); Console.WriteLine(""); Console.WriteLine("제품을 수정합니다."); Console.WriteLine("--------------------------------------------------"); source.Name = "제품2"; source.Category = "그룹2"; UpdateProduct(client, source).GetAwaiter().GetResult(); Console.WriteLine(""); Console.WriteLine("모든 제품을 조회합니다."); Console.WriteLine("--------------------------------------------------"); productList = GetAllProductList(client).GetAwaiter().GetResult(); for(int i = 0; i < productList.Count; i++) { product = productList[i]; Console.WriteLine("{0}, {1}, {2}, {3}", product.ID, product.Name, product.Category, product.Price); } Console.WriteLine(""); Console.WriteLine("제품을 삭제합니다."); Console.WriteLine("--------------------------------------------------"); DeleteProduct(client, source.ID).GetAwaiter().GetResult(); Console.WriteLine(""); Console.WriteLine("모든 제품을 조회합니다."); Console.WriteLine("--------------------------------------------------"); productList = GetAllProductList(client).GetAwaiter().GetResult(); for(int i = 0; i < productList.Count; i++) { product = productList[i]; Console.WriteLine("{0}, {1}, {2}, {3}", product.ID, product.Name, product.Category, product.Price); } Console.WriteLine(""); Console.WriteLine("특정 제품을 조회합니다."); Console.WriteLine("--------------------------------------------------"); product = GetProductByID(client, 3).GetAwaiter().GetResult(); Console.WriteLine("ID : {0}", product.ID ); Console.WriteLine("제품명 : {0}", product.Name ); Console.WriteLine("가격 : {0}", product.Price ); Console.WriteLine("카테고리 : {0}", product.Category); Console.WriteLine(""); Console.WriteLine("카테고리로 제품 리스트를 조회합니다."); Console.WriteLine("--------------------------------------------------"); productList = GetProductListByCategory(client, "Hardware").GetAwaiter().GetResult(); for(int i = 0; i < productList.Count; i++) { product = productList[i]; Console.WriteLine("{0}, {1}, {2}, {3}", product.ID, product.Name, product.Category, product.Price); } Console.WriteLine("--------------------------------------------------"); Console.WriteLine("아무 키나 눌러 주시기 바랍니다."); Console.ReadKey(true); } } #endregion } } |