創建一個Web API 項目
在本教程中,你將使用ASP.NET Web API 來創建一個web API 並返回產品列表。 網頁前端使用jQuery 顯示結果。
選擇ASP.NET Web Application,新建名ProductsApp
在彈出框里選擇空的模板,並把Web API勾選上,點擊OK。
注意
你也可以創建一個“Web API"模板,這個模板將提供ASP.NET MVC幫助頁面等框架。但我使用空模板作為教程,因為我想展示Web API沒有MVC時的運作,一般來說不需要用MVC來使用API。
添加一個Model
一個模型是一個對象,表示應用程序中的數據。ASP.Web API模型可以自動序列化JSON、XML或其他格式,然后序列化數據寫入HTTP響應消息的主體。只要客戶端可以讀取序列化格式,它可以對對象進行反序列化。大多數客戶可以解析XML或JSON。此外,客戶端可以表明它希望的格式通過設置HTTP請求中的Accept標頭信息。
讓我們首先創建一個簡單的模型,代表了一個產品。
如果沒有可見的解決方案資源管理器,單擊“視圖”菜單,選擇“解決方案資源管理器”。在解決方案資源管理器中,右鍵單擊模型文件夾。從上下文菜單中,選擇Add然后選擇類。
類名取"Product"
namespace ProductsApp.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } }
添加一個控制器Controller
在Web API,控制器是一個對象處理HTTP請求。我們將添加一個控制器,可以返回產品列表或指定的單個產品ID。
請注意
如果你有使用ASP.MVC,您已經熟悉控制器。Web API控制器類似MVC控制器,但是繼承ApiController類而不是控制器類。
在解決方案資源管理器中,右鍵單擊控制器文件夾。選擇Add然后選擇控制器。
In the Add Scaffold dialog, select Web API Controller - Empty. Click Add.
控制器名字 "ProductsController". 點擊 Add.
ProductsController.cs 在Controllers文件夾內
using ProductsApp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Http; namespace ProductsApp.Controllers { public class ProductsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; public IEnumerable<Product> GetAllProducts() { return products; } public IHttpActionResult GetProduct(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } } }
復制例子代碼到controller類中。
定義了2個方法返回產品
GetAllProducts
方法返回類型IEnumerable<Product>GetProduct
方法查找單個產品通過ID
就是這樣!你有一個工作的web API。控制器上的每個方法對應於一個或多個uri:
Controller Method | URI |
---|---|
GetAllProducts | /api/products |
GetProduct | /api/products/id |
例如 GetProduct
方法, id 在 URI 是一個占位符,假設id是5: api/products/5
.
調用Web API 通過 Javascript and jQuery
在本節中,我們將添加一個HTML頁面,使用AJAX調用web API。我們將使用jQuery AJAX調用和結果更新頁面。
在解決方案資源管理器中,右鍵單擊項目並選擇添加,然后選擇新的項目。
選擇HTML Page item. Name the page "index.html".
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Product App</title> </head> <body> <div> <h2>All Products</h2> <ul id="products" /> </div> <div> <h2>Search by ID</h2> <input type="text" id="prodId" size="5" /> <input type="button" value="Search" onclick="find();" /> <p id="product" /> </div> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script> <script> var uri = 'api/products'; $(document).ready(function () { // Send an AJAX request $.getJSON(uri) .done(function (data) { // On success, 'data' contains a list of products. $.each(data, function (key, item) { // Add a list item for the product. $('<li>', { text: formatItem(item) }).appendTo($('#products')); }); }); }); function formatItem(item) { return item.Name + ': $' + item.Price; } function find() { var id = $('#prodId').val(); $.getJSON(uri + '/' + id) .done(function (data) { $('#product').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#product').text('Error: ' + err); }); } </script> </body> </html>
得到一個產品列表
發送HTTP GET請求 "/api/products".
$(document).ready(function () {
// Send an AJAX request
$.getJSON(apiUrl)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$('<li>', { text: formatItem(item) }).appendTo($('#products')); }); }); });
通過ID得到產品
發送HTTP GET 請求"/api/products/id"
function find() { var id = $('#prodId').val(); $.getJSON(apiUrl + '/' + id) .done(function (data) { $('#product').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#product').text('Error: ' + err); }); }
運行應用
按下F5 開始 調試應用,頁面如下
輸入ID
如果你輸入一個無效的ID,將返回錯誤
使用F12 來查看HTTP Request and Response
當你使用一個HTTP服務,它可以是非常有用的HTTP請求,請求消息。你可以通過使用Internet Explorer 9的F12開發工具。從Internet Explorer 9,按F12打開工具。單擊網絡選項卡和媒體開始捕捉。現在回到web頁面,按F5重新加載web頁面。Internet Explorer將捕獲瀏覽器和web服務器之間的HTTP流量。摘要視圖顯示一個頁面的所有網絡流量:
定位相對URI的條目“api /產品/”。選擇這個條目並單擊詳細視圖。在細節視圖,有選項卡以查看請求和響應頭和身體。例如,如果您單擊請求頭選項卡,您可以看到客戶端請求“application / json”Accept標頭。
如果你單擊響應主體選項卡,您可以看到產品列表是如何序列化為JSON。其他瀏覽器也有類似的功能。另一個有用的工具是小提琴手,web調試代理。您可以使用Fiddler查看HTTP流量,並構成HTTP請求,這讓你完全控制請求中的HTTP頭。