【WEB API專案實戰乾貨系列】- WEB API入門(一)

DukeCheng發表於2015-10-11

這篇做為這個系列的第一篇,做基本的介紹,有經驗的人可以直接跳到第二部分建立 ProductController。

 

建立 Web API 專案

在這裡我們使用VS2013, .NET 4.5.1建立一個Web API 2的專案

image

選擇專案WEB API模板, 在最下方的MVC主要是預設會自帶微軟的API Helper, 使用MVC釋出

image

在這裡不實用安全

image

 

這樣我們一個專案就初始化好了, 這都要歸功於微軟強大的VS

image

 

F5啟動專案之後, 點選介面上API按鈕可以看到預設建立的API

image

 

這時就可以用上面的地址通過一些測試工具來測試了. 這裡推薦使用fiddler, 後面我們也將廣泛使用這款工具來做除錯.

 

建立我們自己的API-Products API

相關操作步驟如下

新增ProductController

image

image

image

image

 

在這裡我們設計產品相關的API URL如下, 雖然這個不完全符合RESTFul標準,如有糾結的人直接忽略, 這裡主要介紹如何把我們的URL定製成下面這個樣子(也是我們專案中的樣子):

當然這裡的API URL還有其他寫法,這個有興趣的後面章節可以再討論。

我們的 Product API簡單的設計為下面格式:

新增獲取產品分頁API: api/products/product/getList
新增獲取單個產品API: api/products/product/get?productId=產品ID
新增產品新增API: api/products/product/add?productId=產品ID
新增產品更新API: api/products/product/update?productId=產品ID
新增產品刪除API: api/products/product/delete?productId=產品ID

在這裡我們在剛才新新增的ProductController裡中實現上面的API

[RoutePrefix("api/products")]
    public class ProductController : ApiController
    {
        [HttpGet, Route("product/getList")]
        public Page<Product> GetProductList()
        {
            throw new NotImplementedException();
        }

        [HttpGet, Route("product/get")]
        public Product GetProduct(Guid productId)
        {
            throw new NotImplementedException();
        }

        [HttpPost, Route("product/add")]
        public Guid AddProduct(Product product)
        {
            throw new NotImplementedException();
        }

        [HttpPost, Route("product/update")]
        public void UpdateProduct(Guid productId, Product product)
        {
            throw new NotImplementedException();
        }

        [HttpDelete, Route("product/delete")]
        public void DeleteProduct(Guid productId)
        {
            throw new NotImplementedException();
        }
    }

新增之後啟動程式,看到的結果如下

image

 

OK, 到這裡大家加上自己的後端業務邏輯,完成業務層面的操作就可以釋出使用了。

 

本章程式碼: 程式碼下載(程式碼託管在CSDN Code)

相關文章