使用具有 ASP.NET Web Forms 的 Web API
作者:Mike Wasson
本教學課程將逐步引導您完成在 ASP.NET 4.x 中將 Web API 新增至傳統 ASP.NET Web Forms應用程式的步驟。
概觀
雖然 ASP.NET Web API會與 ASP.NET MVC 一起封裝,但可以輕鬆地將 Web API 新增至傳統 ASP.NET Web Forms應用程式。
若要在Web Form應用程式中使用 Web API,有兩個主要步驟:
- 新增衍生自 ApiController 類別的 Web API 控制器。
- 將路由表新增至 Application_Start 方法。
建立Web Form專案
啟動 Visual Studio,然後從 [開始] 頁面中選取 [新增專案]。 或者,從 [ 檔案] 功能表中,選取 [ 新增 ],然後選取 [ 專案]。
在 [ 範本] 窗格中,選取 [ 已安裝的範本 ],然後展開 [Visual C# ] 節點。 在 [Visual C#] 底下,選取 [Web]。 在專案範本清單中,選取[ASP.NET Web Forms應用程式]。 輸入專案的名稱,然後按一下 [ 確定]。
建立模型和控制器
本教學課程使用與消費者入門教學課程相同的模型和控制器類別。
首先,新增模型類別。 在方案總管中,以滑鼠右鍵按一下專案,然後選取 [新增類別]。 將類別命名為 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」,然後按一下 [ 新增]。
[ 新增專案 精靈] 將會建立名為 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 中的路由。
新增Client-Side AJAX
您只需要建立用戶端可以存取的 Web API。 現在,讓我們新增使用 jQuery 呼叫 API 的 HTML 頁面。
例如,請確定主版頁面 (Site.Master) 包含 ContentPlaceHolder
的 ID="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>
接下來,在 區段中新增 jQuery 原始程式檔的 HeaderContent
參考:
<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 資料表。
當您執行應用程式時,它看起來應該像這樣:
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應