使用具有 ASP.NET Web Forms 的 Web API

演講者:Mike Wasson

本教學課程將引導您完成將 Web API 新增至 ASP.NET 4.x 中的傳統 ASP.NET Web Forms 應用程式的步驟。

概觀

儘管 ASP.NET Web API 與 ASP.NET MVC 一起封裝,但將 Web API 新增至傳統的 ASP.NETWeb Forms 應用程式很容易。

若要在 Web Forms 應用程式中使用 Web API,主要有兩個步驟:

  • 新增衍生自 ApiController 類別的 Web API 控制器。
  • 將路由表新增至 Application_Start 方法。

建立 Web Forms 專案

啟動 Visual Studio,並從「開始」頁面選擇「新專案」。 或者,從檔案功能表中選擇新增,然後選擇專案

在「範本」窗格中,選擇「已安裝的範本」並展開「Visual C#」節點。 在「Visual C#」下,選擇「Web」。 在專案範本清單中,選擇「ASP.NET Web Forms 應用程式」。 輸入專案的名稱,然後按一下「確定」。

Screenshot of the new project template pane, showing the available menu options for creating the new web A S P dot NET application form.新專案範本窗格的螢幕擷取畫面,顯示用於建立新 Web A S P.NET 應用程式表單的可用功能表選項。

建立模型和控制器

本教學使用與快速入門教學中相同的模型和控制器類。

首先,加入一個模型類別。 在「方案總管」中,以滑鼠右鍵按一下該專案並選擇「新增類別」。 將類別命名為 Product,並加入以下實作:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Category { get; set; }
}

接下來,將 Web API 控制器新增到專案中。控制器是處理 Web API HTTP 請求的物件。

在 [方案總管] 中,右鍵點擊專案。 選擇新增項目

方案總管中功能表選項的螢幕擷取畫面,顯示如何新增專案項目的圖解指南。

在「已安裝的範本」下,展開 Visual C# 並選擇「Web」。 然後,從範本清單中選擇 Web API 控制器類別。 將控制器命名為「ProductsController」並點擊「新增」。

Screenshot showing of how to add a new web item as a web A P I controller class, labeling it Product Controller in the name field.螢幕擷取畫面顯示如何將新 Web 項目新增為 Web API 控制器類別,並在名稱欄位中將它標示為「產品控制器」。

新增項目精靈將會建立一個名為 ProductsController.cs 的檔案。 刪除精靈中的方法,然後新增以下方法:

namespace WebForms
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Web.Http;

    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 Product GetProductById(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return product;
        }

        public IEnumerable<Product> GetProductsByCategory(string category)
        {
            return products.Where(
                (p) => string.Equals(p.Category, category,
                    StringComparison.OrdinalIgnoreCase));
        }
    }
}

有關此控制器中程式碼的更多資訊,請參閱「快速入門」教學課程。

新增路由資訊

接下來,我們將新增一個 URI 路由,以便將「/api/products/」形式的 URI 路由到控制器。

方案總管中,雙擊 Global.asax 以開啟程式碼隱藏檔案 Global.asax.cs。 加入以下 using 語句。

using System.Web.Http;

然後將以下程式碼加入 Application_Start 方法:

RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = System.Web.Http.RouteParameter.Optional }
);

有關路由表的詳細資訊,請參閱〈ASP.NET Web API 中的路由〉。

新增用戶端 AJAX

這就是建立用戶端可以存取的 Web API 所需的全部步驟。 現在讓我們新增一個使用 jQuery 呼叫 API 的 HTML 頁面。

確保您的主版頁面 (例如 Site.Master) 包含 ContentPlaceHolderID="HeadContent"

<asp:ContentPlaceHolder runat="server" ID="HeadContent"></asp:ContentPlaceHolder>

開啟檔案 Default.aspx。 替換主要內容區段中的樣板文字,如下所示:

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" 
    AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForms._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>Products</h2>
    <table>
    <thead>
        <tr><th>Name</th><th>Price</th></tr>
    </thead>
    <tbody id="products">
    </tbody>
    </table>
</asp:Content>

接下來,在以下 HeaderContent 區段中加入對 jQuery 原始文件的引用:

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
</asp:Content>

注意:您可以透過將檔案從方案總管拖曳到程式碼編輯器視窗中來輕鬆新增指令碼參考。

方案總管和程式碼編輯器視窗的截圖,使用綠色箭頭來顯示將指令碼放入程式碼中的位置。

在 jQuery 指令碼標籤下方,新增以下指令碼區塊:

<script type="text/javascript">
    function getProducts() {
        $.getJSON("api/products",
            function (data) {
                $('#products').empty(); // Clear the table body.

                // Loop through the list of products.
                $.each(data, function (key, val) {
                    // Add a table row for the product.
                    var row = '<td>' + val.Name + '</td><td>' + val.Price + '</td>';
                    $('<tr/>', { html: row })  // Append the name.
                        .appendTo($('#products'));
                });
            });
        }

        $(document).ready(getProducts);
</script>

載入文件時,此指令碼會向「api/products」發出 AJAX 請求。 此請求傳回 JSON 格式的產品清單。 此指令碼將產品資訊新增至 HTML 表中。

當您運行該應用程式時,它應該如下所示:

顯示產品標籤、名稱和價格的網頁瀏覽器螢幕截圖,作為其外觀的範例。