using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ProductStore.Models { //商品實體類 public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProductStore.Models { //商品接口 interface IProductRepository { IEnumerable<Product> GetAll(); Product Get(int id); Product Add(Product item); void Remove(int id); bool Update(Product item); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ProductStore.Models { //商品操作類 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; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using ProductStore.Models; using System.Text; //控制器 namespace ProductStore.Controllers { public class ProductsController : ApiController { /* * 微軟的web api是在vs2012上的mvc4項目綁定發行的,它提出的web api是完全基於RESTful標准的, * 完全不同於之前的(同是SOAP協議的)wcf和webService,它是簡單,代碼可讀性強的,上手快的, * 如果要拿它和web服務相比,我會說,它的接口更標准,更清晰,沒有混亂的方法名稱, * * 有的只有幾種標准的請求,如get,post,put,delete等,它們分別對應的幾個操作,下面講一下: * GET:生到數據列表(默認),或者得到一條實體數據 * POST:添加服務端添加一條記錄,記錄實體為Form對象 * PUT:添加或修改服務端的一條記錄,記錄實體的Form對象,記錄主鍵以GET方式進行傳輸 * DELETE:刪除 服務端的一條記錄 */ static readonly IProductRepository repository = new ProductRepository(); public IEnumerable<Product> GetAllProducts() { return repository.GetAll(); } public Product GetProduct(int id) { Product item = repository.Get(id); if (item == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return item; } public IEnumerable<Product> GetProductsByCategory(string category) { return repository.GetAll().Where( p => string.Equals(p.Category, category, StringComparison.OrdinalIgnoreCase)); } public HttpResponseMessage PostProduct(Product item) { item = repository.Add(item); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("add success", System.Text.Encoding.UTF8, "text/plain") }; } public void PutProduct(int id, Product product) { product.Id = id; if (!repository.Update(product)) { throw new HttpResponseException(HttpStatusCode.NotFound); } } public void DeleteProduct(int id) { repository.Remove(id); } } }
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %> <!DOCTYPE html> <html> <head runat="server"> <meta name="viewport" content="width=device-width" /> <title>測試Web Api - Jquery調用</title> <script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> </head> <body> <div> <fieldset> <legend>測試Web Api </legend> <a href="javascript:add()">添加(post)</a> <a href="javascript:update(1)">更新(put)</a> <a href="javascript:deletes(1)">刪除(delete)</a> <a href="javascript:getall()">列表(Get)</a> <a href="javascript:getone()">實體(Get)</a> </fieldset> <table id="products"> <thead> <tr><th>ID</th><th>Name</th><th>Category</th><th>Price</th></tr> </thead> <tbody id="looptr"> </tbody> </table> <script type="text/javascript"> $(function () { getall(); }); //獲取列表 function getall() { var str = ""; $.getJSON("/api/products", function (products) { alert(JSON.stringify(products)); $.each(products, function (index, product) { str += "<tr>" str += "<td>" + products[index].Id + "</td>"; str += "<td>" + products[index].Name + "</td>"; str += "<td>" + products[index].Category + "</td>"; str += "<td>" + products[index].Price + "</td>"; str += "<tr>" }); $("#looptr").html(str); }); } //獲取某條信息 function getone() { var str = ""; $.getJSON("/api/products/1", function (product) { alert(JSON.stringify(product)); str += "<tr>" str += "<td>" + product.Id + "</td>"; str += "<td>" + product.Name + "</td>"; str += "<td>" + product.Category + "</td>"; str += "<td>" + product.Price + "</td>"; str += "<tr>" $("#looptr").html(str); }); } //新增 function add() { $.ajax({ url: "/api/products/", type: "POST", data: { "Id": 4, "Name": "test", "Category": "Parry", "Price": 239 }, success: function (data) { alert(JSON.stringify(data)); } }); } //更新 function update(id) { $.ajax({ url: "/api/products?id=4", type: "Put", data: { "Id": 1, "Name": "moditest", "Category": "Parry", "Price": 89 }, success: function (data) { alert(JSON.stringify(data)); } }); } //刪除 function deletes(id) { $.ajax({ url: "/api/products/4", type: "DELETE", success: function (data) { alert(data); } }); } </script> </div> </body> </html>