2. What is ASP.NET Web API?
ASP.NET
Web API is a framework that makes it easy to
build HTTP services that reach a broad range of
clients, including browsers and mobile devices.
ASP.NET Web API is an ideal platform for building
RESTful applications on the .NET Framework.
ASP.NET
Web API 使用的是 HTTP Application
Protocol。
ASP.NET
Web API就是簡單的HTTP服務。
2014/1/14
2
3. HTTP Method在RESTful Web Service中的典型應用
REST是一種設計風格,不是一種標準或協定,REST的核心概念就是「如何正確地使用網頁
標準(Web Standards)」。
RESTful Web API是一個使用HTTP協定並遵循REST原則的Web Service 。
Operation
HTTP Method
Create
POST
Read
http://example.com/resources/
http://example.com/resources/123
新增/追加一組新的Resources
新增/追加一個新的Resource
GET
取得Resources集合中的所有詳細內容
取得指定Resource的詳細內容
Update
PUT
以新的Resources更新目前的Resources
更新指定的某個Resource,如果指定的
Resource不存在,就會新增一個
Delete
DELETE
刪除整組Resources
刪除指定的Resource
2014/1/14
3
4. Controller
→在ASP.NET MVC 與在 ASP.NET Web API之間的區別
Controller所繼承的Class不同,那麼
Controller內的Action所處理的行為模式也不
相同:
MVC
Controller根據Action所定義的行為模式回傳
View與資料
Web
API的ApiController,它的Action不會回傳
View,而是回傳一組資料(XML, JSON…)
提供Web
API Service的Controller一定是繼
承自ApiController
2014/1/14
4
5. ASP.NET Web API的兩大主軸
Models
在Repository
Patten中定義資料存取的運作基礎,把所有存取資
料庫的CRUD方法都集中在Repository Class內
ApiControllers
把如何處理Model的方法封裝成一個一個的API方法,只要透過API方法
之間的約定去呼叫API方法,就能夠以相當便利的方式完成CRUD的操
作
2014/1/14
5
6. ASP.NET Web API 與 Route (1/2)
•
Web API 使用 HTTP Methods (GET, POST, PUT, DELETE…)來選
擇 Action,而不是使用 URI 路徑來選擇 Action。
•
Web API 是使用 API Controller Class 來處理HTTP Request,當
Web API 接收到一個 HTTP Request 時,會將此HTTP請求 Route
到一個 API 方法。Route 規則表會決定哪一個 API 會被使用。如果
沒有符合的 Route ,那個在 Client 端會收到一個 HTTP 404 的錯誤
狀態。
•
ASP.NET Web API是看 ApiController Name 來決定,ASP.NET
MVC 則是看 Controller Name 與 Action Name 來決定
2014/1/14
6
7. Web API 與 Route (2/2)
WebApiConfig
name: 是要對應的 Route 名稱
routeTemplate: Route的範本
defaults: 包含預設 Route value 的 object
ProductsController
符合
URI: api/products/123
api/products?id=123
不符合
URI: products/123
2014/1/14
7
8. 參考
網站:
Creating a Web API that Supports CRUD Operations
Routing and Action Selection
http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supportscrud-operations
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-actionselection
Routing in ASP.NET Web API
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
書籍:
ASP.NET MVC 4網站開發美學
2014/1/14
8