1.WebApi是什麼
ASP.NET Web API 是一種框架,用於輕鬆構建可以由多種客戶端(包括瀏覽器和移動裝置)訪問的 HTTP 服務。ASP.NET Web API 是一種用於在 .NET Framework 上構建 RESTful 應用程式的理想平臺。
可以把WebApi看成Asp.Net專案型別中的一種,其他專案型別諸如我們熟知的WebForm專案,Windows窗體專案,控制檯應用程式等。
WebApi型別專案的最大優勢就是,開發者再也不用擔心客戶端和伺服器之間傳輸的資料的序列化和反序列化問題,因為WebApi是強型別的,可以自動進行序列化和反序列化,一會兒專案中會見到。
下面我們建立了一個WebApi型別的專案,專案中對產品Product進行增刪改查,Product的資料存放在List<>列表(即記憶體)中。
2.頁面執行效果
如圖所示,可以新增一條記錄; 輸入記錄的Id,查詢出該記錄的其它資訊; 修改該Id的記錄; 刪除該Id的記錄。
3.二話不說,開始建專案
1)新建一個“ASP.NET MVC 4 Web 應用程式”專案,命名為“ProductStore”,點選確定,如圖
2)選擇模板“Web API”,點選確定,如圖
3)和MVC型別的專案相似,構建程式的過程是先建立資料模型(Model)用於存取資料, 再建立控制器層(Controller)用於處理髮來的Http請求,最後構造顯示層(View)用於接收使用者的輸入和使用者進行直接互動。
這裡我們先在Models資料夾中建立產品Product類: Product.cs,如下:
- using System;
- using System.Collections.Generic;
- 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; }
- }
- }
4)試想,我們目前只有一個Product型別的物件,我們要編寫一個類對其實現增刪改查,以後我們可能會增加其他的型別的物件,再需要編寫一個對新型別的物件進行增刪改查的類,為了便於拓展和呼叫,我們在Product之上構造一個介面,使這個介面約定增刪改查的方法名稱和引數,所以我們在Models資料夾中新建一個介面: IProductRepository.cs ,如下:
- 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);
- }
- }
5)然後,我們實現這個介面,在Models資料夾中新建一個類,具體針對Product型別的物件進行增刪改查存取資料,並在該類的構造方法中,向List<Product>列表中存入幾條資料,這個類叫:ProductRepository.cs,如下:
- 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 = ;
- 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 == -)
- {
- return false;
- }
- products.RemoveAt(index);
- products.Add(item);
- return true;
- }
- }
- }
此時,Model層就構建好了。
6)下面,我們要構建Controller層,在此之前,先回顧一下Http中幾種請求型別,如下
get 型別 用於從伺服器端獲取資料,且不應該對伺服器端有任何操作和影響
post 型別 用於傳送資料到伺服器端,建立一條新的資料,對伺服器端產生影響
put 型別 用於向伺服器端更新一條資料,對伺服器端產生影響 (也可建立一條新的資料但不推薦這樣用)
delete 型別 用於刪除一條資料,對伺服器端產生影響
這樣,四種請求型別剛好可對應於對資料的 查詢,新增,修改,刪除。WebApi也推薦如此使用。在WebApi專案中,我們請求的不再是一個具體頁面,而是各個控制器中的方法(控制器也是一種類,預設放在Controllers資料夾中)。下面我們將要建立一個ProductController.cs控制器類,其中的方法都是以“Get Post Put Delete”中的任一一個開頭的,這樣的開頭使得Get型別的請求傳送給以Get開頭的方法去處理,Post型別的請求交給Post開頭的方法去處理,Put和Delete同理。
而以Get開頭的方法有好幾個也是可以的,此時如何區分到底交給哪個方法執行呢?這就取決於Get開頭的方法們的傳入引數了,一會兒在程式碼中可以分辨。
構建Controller層,在Controllers資料夾中建立一個ProductController.cs控制器類,如下:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using ProductStore.Models;
- using System.Web.Http;
- using System.Net;
- using System.Net.Http;
- namespace ProductStore.Controllers
- {
- public class ProductsController : ApiController
- {
- static readonly IProductRepository repository = new ProductRepository();
- //GET: /api/products
- public IEnumerable<Product> GetAllProducts()
- {
- return repository.GetAll();
- }
- //GET: /api/products/id
- public Product GetProduct(int id)
- {
- Product item = repository.Get(id);
- if (item == null)
- {
- throw new HttpResponseException(HttpStatusCode.NotFound);
- }
- return item;
- }
- //GET: /api/products?category=category
- public IEnumerable<Product> GetProductsByCategory(string category)
- {
- return repository.GetAll().Where(p=>string.Equals(p.Category,category,StringComparison.OrdinalIgnoreCase));
- }
- //POST: /api/products
- public HttpResponseMessage PostProduct(Product item)
- {
- item = repository.Add(item);
- var response = Request.CreateResponse<Product>(HttpStatusCode.Created,item);
- string uri = Url.Link("DefaultApi", new { id=item.Id});
- response.Headers.Location = new Uri(uri);
- return response;
- }
- //PUT: /api/products/id
- public void PutProduct(int id, Product product)
- {
- product.Id = id;
- if (!repository.Update(product))
- {
- throw new HttpResponseException(HttpStatusCode.NotFound);
- }
- }
- //Delete: /api/products/id
- public void DeleteProduct(int id)
- {
- Product item = repository.Get(id);
- if (item == null)
- {
- throw new HttpResponseException(HttpStatusCode.NotFound);
- }
- repository.Remove(id);
- }
- }
- }
使該類繼承於ApiController類,在其中實現處理各種Get,Post,Put,Delete型別Http請求的方法。
每一個方法前都有一句註釋,標識了該方法的針對的請求的型別(取決於方法的開頭),以及要請求到該方法,需要使用的url。
這些url是有規律的,見下圖:
api是必須的,products對應的是ProductsControllers控制器,然後又Http請求的型別和url的後邊地址決定。
這裡,我們除了第三個“Get a product by category”,其他方法都實現了。
7)最後,我們來構建View檢視層,我們更改Views資料夾中的Home資料夾下的Index.cshtml檔案,這個檔案是專案啟動頁,如下:
- <div id="body">
- <script src="~/Scripts/jquery-1.8.2.min.js"></script>
- <section >
- <h2>新增記錄</h2>
- Name:<input id="name" type="text" /><br />
- Category:<input id="category" type="text" />
- Price:<input id="price" type="text" /><br />
- <input id="addItem" type="button" value="新增" />
- </section>
- <section>
- <br />
- <br />
- <h2>修改記錄</h2>
- Id:<input id="id2" type="text" /><br />
- Name:<input id="name2" type="text" /><br />
- Category:<input id="category2" type="text" />
- Price:<input id="price2" type="text" /><br />
- <input id="showItem" type="button" value="查詢" />
- <input id="editItem" type="button" value="修改" />
- <input id="removeItem" type="button" value="刪除" />
- </section>
- </div>
8)然後我們給頁面新增js程式碼,對應上面的按鈕事件,用來發起Http請求,如下:
- <script>
- //用於儲存使用者輸入資料
- var Product = {
- create: function () {
- Id: "";
- Name: "";
- Category: "";
- Price: "";
- return Product;
- }
- }
- //新增一條記錄 請求型別:POST 請求url: /api/Products
- //請求到ProductsController.cs中的 public HttpResponseMessage PostProduct(Product item) 方法
- $("#addItem").click(function () {
- var newProduct = Product.create();
- newProduct.Name = $("#name").val();
- newProduct.Category = $("#category").val();
- newProduct.Price = $("#price").val();
- $.ajax({
- url: "/api/Products",
- type: "POST",
- contentType: "application/json; charset=utf-8",
- data: JSON.stringify(newProduct),
- success: function () {
- alert("新增成功!");
- },
- error: function (XMLHttpRequest, textStatus, errorThrown) {
- alert("請求失敗,訊息:" + textStatus + " " + errorThrown);
- }
- });
- });
- //先根據Id查詢記錄 請求型別:GET 請求url: /api/Products/Id
- //請求到ProductsController.cs中的 public Product GetProduct(int id) 方法
- $("#showItem").click(function () {
- var inputId = $("#id2").val();
- $("#name2").val("");
- $("#category2").val("");
- $("#price2").val("");
- $.ajax({
- url: "/api/Products/" + inputId,
- type: "GET",
- contentType: "application/json; charset=urf-8",
- success: function (data) {
- $("#name2").val(data.Name);
- $("#category2").val(data.Category);
- $("#price2").val(data.Price);
- },
- error: function (XMLHttpRequest, textStatus, errorThrown) {
- alert("請求失敗,訊息:" + textStatus + " " + errorThrown);
- }
- });
- });
- //修改該Id的記錄 請求型別:PUT 請求url: /api/Products/Id
- //請求到ProductsController.cs中的 public void PutProduct(int id, Product product) 方法
- $("#editItem").click(function () {
- var inputId = $("#id2").val();
- var newProduct = Product.create();
- newProduct.Name = $("#name2").val();
- newProduct.Category = $("#category2").val();
- newProduct.Price = $("#price2").val();
- $.ajax({
- url: "/api/Products/" + inputId,
- type: "PUT",
- data: JSON.stringify(newProduct),
- contentType: "application/json; charset=urf-8",
- success: function () {
- alert("修改成功! ");
- },
- error: function (XMLHttpRequest, textStatus, errorThrown) {
- alert("請求失敗,訊息:" + textStatus + " " + errorThrown);
- }
- });
- });
- //刪除輸入Id的記錄 請求型別:DELETE 請求url: /api/Products/Id
- //請求到ProductsController.cs中的 public void DeleteProduct(int id) 方法
- $("#removeItem").click(function () {
- var inputId = $("#id2").val();
- $.ajax({
- url: "/api/Products/" + inputId,
- type: "DELETE",
- contentType: "application/json; charset=uft-8",
- success: function (data) {
- alert("Id為 " + inputId + " 的記錄刪除成功!");
- },
- error: function (XMLHttpRequest, textStatus, errorThrown) {
- alert("請求失敗,訊息:" + textStatus + " " + errorThrown);
- }
- });
- });
- </script>
這裡,WebApi的一個簡單的增刪改查專案就完成了,選擇執行專案即可測試。注意到,其中用ajax發起請求時,傳送到伺服器端的資料直接是一個json字串,當然這個json字串中每個欄位要和Product.cs類中的每個欄位同名對應,在伺服器端接收資料的時候,我們並沒有對接收到的資料進行序列化,而返回資料給客戶端的時候也並沒有對資料進行反序列化,大大節省了以前開發中不停地進行序列化和反序列化的時間。