asp.net mvc 4 web api 開發簡介
DESCRIPTION
TRANSCRIPT
C#_ASP.NET_ 應用程式開發講座
( 第四天 )ASP.NET MVC Web API 簡介
何謂 RESTful
認識 ASP.NET MVC Web API ASP.NET MVC Web API 基本架構 資料的 REST 介面 如何建立 ASP.NET MVC Web API 應用程式 第一個 Web API 應用程式 CRUD 如何透過 Web API 傳遞 ( 圖片/ Binary)
大綱
同 WCF Data Service ,且支援 RESTful 介面,但是它更簡化,更簡單,易於實作。
只支援 HTTP 協定,透過 GET/POST 方式提供遠端使用 XML 或 JSON 資料格式進行呼叫與使用。
更容易讓多種裝置使用:如平板、智慧型裝置、桌上型電腦、其他平台服務、瀏覽器…
支援非同步執行特性,有更佳之延展性 支援 ASP.NET MVC 的 Routing 功能 強行別的 HttpRequestMessage 與
HttpResponseMessage ,因此模型繫結與驗證更加容易。
認識 ASP.NET MVC Web API
ASP.NET MVC Web API 基本架構
資料的 REST 介面
• 最根本的模式。• Entities 與 associations 資源與連結。
Entity Data Model
•每種資源都可以由 URI 來定位。•具有彈性的資料擷取 URI 結構。URIs
•將資料視為資源,使用 HTTP 動詞來操作它。•平衡快取,代理,驗證,…HTTP
•AtomPub, JSON資料格式
取得 CustomerID=‘ALFKI’ 的資料
使用 URL 來下查詢條件 (1)
使用 top 語句,取得第一筆資料
使用 URL 來下查詢條件 (2)
選擇 Web API 類型的應用程式。 建立 Model & ViewModel 建立 apiController 建立存取 apiController 的 View
如何建立 ASP.NET MVC Web API 應用程式
選擇 Web API 類型的應用程式
可以選擇使用 EDM 或仿間其他種 ORM 工具,如Nhibernate 等。
也可以自行定義 ViewModel 與 DAL 資料層。
建立 Model & ViewModel
建立 apiController 直接在 Controller 資料夾點選右鍵,加入控制器
可透過範本自動建立 若自行定義 ViewModel 則使用 ViewModel 來
建立
建立存取 apiController 的 View
Demo
第一個 Web API 應用程式 CRUD
如何透過 Web API 傳遞 ( 圖片/Binary)HttpResponseMessage response = new HttpResponseMessage(); NorthwindEntities context = new NorthwindEntities(); var result = from Emp in context.Employees
where Emp.EmployeeID == id select Emp;
var emp = result.FirstOrDefault(); if (emp != null) {
response.Content = new StreamContent(new MemoryStream(emp.Photo));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");} return response;
使用 Windows 8 Store App 來存取
Demo
如何透過 Web API 傳遞 ( 圖片/ Binary)(2)
Q&A