顯示具有 Web API 標籤的文章。 顯示所有文章
顯示具有 Web API 標籤的文章。 顯示所有文章

2013年10月11日 星期五

【Web API】建立一個頁面,透過 Web API 來建立資料

1. 繼前一篇文章,可以取到資料後,來練習一下如何新增資料
http://tsengpm.blogspot.tw/2013/10/web-api-web-api.html


2. 其實好像也不難,只要 javascript 宣告一個一樣的 object,然後透過 JSON.stringify 轉成 Json 物件傳進去就好

3. 以下是程式碼

Javascript


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function AddData() {
 var product = {
  Id: document.getElementById('txtId').value,
  Name: document.getElementById('txtName').value,
  Category: document.getElementById('txtCategory').value,
  Price: document.getElementById('txtPrice').value
 };
 $.ajax({
  url: '/api/Products/PostProduct',
  type: 'POST',
  data: JSON.stringify(product),
  contentType: "application/json;charset=utf-8",
  success: function (data) {
   alert('新增成功');
   GetData();
  },
  error: function () {
   alert('新增失敗');
  }
 });
}

Html

1
2
3
4
5
<input type="text" id="txtId" value="" /><BR />
<input type="text" id="txtName" value="" /><BR />
<input type="text" id="txtCategory" value="" /><BR />
<input type="text" id="txtPrice" value="" /><BR />
<input type="button" id="btnAdd" value="新增資料" onclick="AddData();" />



【Web API】 回傳 json 格式

1. 繼上一篇文章, 回傳的是 xml,但是現在好像都用 json 比較多,所以改了一下,讓 Web API 也回傳 json
http://tsengpm.blogspot.tw/2013/10/crud-web-api.html

2. 在 Global.asax 中,加入一段程式

1
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();


3. 這樣就會回傳 json 了

【Web API】 建立一個具有 CRUD 功能的 Web API

1. 什麻是 CRUD?
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; }
    }
5. 在 Model 內新增一個Interface,IProductRepository

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