ANS:Create / Read / Update / Delete
http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations
2. 開始建立專案,選擇ASP.NET MVC應用程式
3. 選擇Web API範本
4. 在 Model 中新增一個類別,Product
1 2 3 4 5 6 7 | public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } |
1 2 3 4 5 6 7 8 | public interface IProductRepository { IEnumerable<Product> GetAll(); Product Get(int id); Product Add(Product item); void Remove(int id); bool Update(Product item); } |
6. 然後再新增一個類別,名叫 ProductRepository
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 | public class ProductRepository : IProductRepository { private List<Product> products = new List<Product>(); private int _nextId = 1; public ProductRepository() { Add(new Product { Name = "Tomato soup", Category = "Groceries", Price = 1.39M }); Add(new Product { Name = "Yo-yo", Category = "Toys", Price = 3.75M }); Add(new Product { Name = "Hammer", Category = "Hardware", Price = 16.99M }); } public IEnumerable<Product> GetAll() { return products; } public Product Get(int id) { return products.Find(p => p.Id == id); } public Product Add(Product item) { if (item == null) { throw new ArgumentNullException("item"); } item.Id = _nextId++; products.Add(item); return item; } public void Remove(int id) { products.RemoveAll(p => p.Id == id); } public bool Update(Product item) { if (item == null) { throw new ArgumentNullException("item"); } int index = products.FindIndex(p => p.Id == item.Id); if (index == -1) { return false; } products.RemoveAt(index); products.Add(item); return true; } } |
7. 新增一個 Controller,ProductsController
8. 注意是繼承 ApiController
1 | static readonly IProductRepository repository = new ProductRepository(); |
9. 撰寫 Read 的程式碼
1 2 3 4 | public IEnumerable<Product> GetAllProducts() { return repository.GetAll(); } |
10. 傳入id取得資料
1 2 3 4 5 6 7 8 9 | public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return item; } |
11. 新增資料
1 2 3 4 5 | public Product PostProduct(Product item) { item = repository.Add(item); return item; } |
12. 修改資料
1 2 3 4 5 6 7 8 | public void PutProduct(int id, Product product) { product.Id = id; if (!repository.Update(product)) { throw new HttpResponseException(HttpStatusCode.NotFound); } } |
13. 刪除資料
1 2 3 4 5 6 7 8 9 10 | public void DeleteProduct(int id) { Product item = repository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } repository.Remove(id); } |
14. 最後來測試一下資料,因為我的 Controller 叫做 ProductsController ,所以網址就會變成 http://XXXX/api/Products
沒有留言:
張貼留言