【Web API系列教程】1.1 — ASP.NET Web API入門

來源:互聯網
上載者:User

標籤:type   hid   工具   pretty   ebs   產生   strong   linq   展開   

前言

HTTP不僅僅服務於web頁面。同一時候也是構建暴露服務和資料的API的強大平台。HTTP有著簡單、靈活和無處不在的特點。你能想到的差點兒全部平台都包括有一個HTTP庫。所以HTTP服務能夠遍及廣泛的client,包括瀏覽器、行動裝置和傳統傳統型應用程式。

ASP.NET Web API是一個在.NET架構上構建web API的架構。在本教程中,你將使用ASP.NET Web API來建立一個返回產品列表的web API。

建立Web API項目

在本教程中,你將使用ASP.NET Web API來建立一個返回產品列表的web API。

前端頁面使用jQuery來顯示結果。

開啟Visual Studio並在開始頁面選擇New Project。或者在File目錄下選擇New。然後選擇Project。

在Template面板中,選擇Installed Templates。然後展開Visual C#節點。

在Visual C#節點下。選擇Web。

在項目模板列表中。選擇ASP.NET Web Application。

命名項目為“ProductsApp”並點擊OK。

在NEW ASP.NET Project對話方塊中,選擇Empty模板。在”Add folders and core references for”,選中Web API。點擊OK。

凝視:你也能夠用“Web API”模板來建立Web API。

Web API模板使用了ASP.NET MVC來提供API的協助頁面。我在本教程中使用Empty模板是由於我希望不用MVC來展示Web API。通常,你不必瞭解ASP.NET MVC就能使用Web API。

加入模型

模型是在你的應用程式中表示資料的對象。

ASP.NET Web API能夠將你的模型自己主動序列化成JSON、XML或其它格式。然後將其序列化資料寫入到HTTP響應訊息的body中。

僅僅要client能夠讀取序列化格式,它就能夠還原序列化出對象。

差點兒全部client都能解析XML或JSON。並且。client還能通過在HTTP請求的Accept header中設定來指明它想要的格式。

讓我們來建立一個表示產品的簡單模型吧。

假設Solution Explorer沒有顯示出來,點擊View菜單,然後選擇Solution Explorer。在Solution Explorer中。右擊Models目錄。從操作功能表中選擇Add。然後選擇Class。

命名該類為“Product”。加入下面屬性到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; }    }}
加入控制器

在Web API中,控制器(controller)是處理HTTP請求的對象。

我們將加入一個能夠依據ID來返回多個或一個產品的控制器。

備忘:假設你還沒有使用過ASP.NET MVC,你應該已經對控制器非常熟悉了。Web API的控制器和MVC的控制器非常相近。可是它繼承的是ApiController而不是Controller。

在Solution Explorer中,右擊Controllers目錄。選擇Add,然後選擇Controller。

在Add Scaffold對話方塊中,選擇Web API Controller – Empty。

點擊Add。

在Add Controller對話方塊,給控制器命名為”ProductsController”。

點擊Add。

接下來便會在Controllers目錄下建立一個名為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);        }    }}

為了讓示範範例簡單化,products被儲存在控制器類中的固定數組中。當然,在實際應用程式中,你可能想要查詢資料庫或使用其它外部資料源。

控制器定義了兩個返回產品的方法:
1. GetAllProducts方法將整個產品列表作為IEnumerable類型返回。
2. GetProduct方法通過它的ID來尋找單個產品。

沒錯,你已經有一個能夠使用的web API了。控制器上的每一個方法都相應一個或多個URI:

Controlle Method URI
GetAllProducts /api/products
GetProduct /api/products/id

對於GetProduct方法,URI中的id是一個預留位置。比如。為了得到一個ID為5的產品,URI是api/products/5。

使用JavaScript和jQuery來調用Web API

在本節中,我們將加入一個使用AJAX來調用Web API的HTML頁面。我們將使用jQuery來產生AJAX調用並用返回結果來更新頁面。

在Solution Explorer中,右擊項目並選擇Add,然後選擇New Item。

在Add New Item對話方塊中,選擇Visual C#下的Web節點,然後選擇HTML 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>

有好幾個方法去得到jQuery。在本例中,我使用Microsoft Ajax CDN。你也能夠在http://jquery.com/下載它。讓ASP.NET “Web API”項目包括jQuery。

得到產品列表

為了得到Products列表。能夠發送一個HTTP的GET請求到“/api/products”。

jQuery的getJSON函數會發送AJAX請求。

當中包括了JSON對象數組。done函數指定了一個當請求成功時觸發的回調。在回調中。我們用產品資訊更新DOM。

$(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得到產品

假設想要通過ID來取得產品,能夠發送HTTP的GET請求到”/api/products/id“,當中id就是產品的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);        });}

我們仍然使用getJSON來發送AJAX請求,可是這次我們將ID放到URI請求中。它的響應會是一個代表了單個產品的JSON對象。

執行應用程式

按F5開始調試應用程式,web頁面看起來會是下面這樣:

為了通過ID獲得產品,輸入ID並點擊Search。

假設你輸入了一個無效的ID,那麼server就會返回HTTP錯誤訊息。

使用F12查看HTTP請求和響應

當你工作於HTTP服務時,假設能夠查看HTTP請求和響應的具體無疑是非常有協助的。

你能夠在IE9中使用F12開發人員工具來做這些操作。在IE9中,按F12來開啟工具。點擊Network面板,並點擊Start Capturing。如今返回到web頁面,並按F5來又一次載入web頁面。

IE將會捕捉到瀏覽器和webserver之間的HTTP傳輸。顯示了一個頁面的全部HTTP傳輸。

定位到相對URI”api/products/“。選中並點擊Go to detailed view。

在具體視圖中,這裡多個面板用於查看請求和響應的header和body。

比如。假設你點擊Request headers,你就會看到client在Accept header請求了”application/json“。

假設你點擊了Response body,你就會看到產品列表怎樣被序列化成JSON。其它瀏覽器也有類似的功能。還有一個實用的工具是Fiddler,它是一個web調試代理工具。你能夠使用Fiddler來查看HTTP傳輸,也能夠合成HTTP請求,後者能夠給予你在請求上對於HTTP頭部的全然控制。

【Web API系列教程】1.1 — ASP.NET Web API入門

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.