向 ASP.NET Web 窗体使用 Web APIUsing Web API with ASP.NET Web Forms

作者: Mike Wassonby Mike Wasson

本教程将指导你完成将 Web API 添加到 ASP.NET 4.x 中的传统 ASP.NET Web 窗体应用程序的步骤。This tutorial walks you through the steps to add Web API to a traditional ASP.NET Web Forms application in ASP.NET 4.x.

概述Overview

尽管 ASP.NET Web API 与 ASP.NET MVC 一起打包,但可以轻松地将 Web API 添加到传统的 ASP.NET Web 窗体应用程序。Although ASP.NET Web API is packaged with ASP.NET MVC, it is easy to add Web API to a traditional ASP.NET Web Forms application.

若要在 Web 窗体应用程序中使用 Web API,需要执行两个主要步骤:To use Web API in a Web Forms application, there are two main steps:

  • 添加一个派生自ApiController类的 Web API 控制器。Add a Web API controller that derives from the ApiController class.
  • 将路由表添加到应用程序_Start方法。Add a route table to the Application_Start method.

创建 Web 窗体项目Create a Web Forms Project

启动 Visual Studio,然后从起始页中选择 "新建项目"。Start Visual Studio and select New Project from the Start page. 或者,从 "文件" 菜单中选择 "新建",然后选择 "项目"。Or, from the File menu, select New and then Project.

在 "模板" 窗格中,选择 "已安装模板",然后展开视觉对象C# 节点。In the Templates pane, select Installed Templates and expand the Visual C# node. " C#视觉对象" 下选择 " Web"。Under Visual C#, select Web. 在项目模板列表中,选择 " ASP.NET Web 窗体应用程序"。In the list of project templates, select ASP.NET Web Forms Application. 输入项目的名称,然后单击 "确定"Enter a name for the project and click OK.

创建模型和控制器Create the Model and Controller

本教程使用与入门教程相同的模型和控制器类。This tutorial uses the same model and controller classes as the Getting Started tutorial.

首先,添加一个模型类。First, add a model class. 解决方案资源管理器中,右键单击项目,然后选择 "添加类"。In Solution Explorer, right-click the project and select Add Class. 将类命名为 "Product",并添加以下实现:Name the class Product, and add the following implementation:

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 请求的对象。Next, add a Web API controller to the project., A controller is the object that handles HTTP requests for Web API.

在“解决方案资源管理器”中,右键单击项目。In Solution Explorer, right-click the project. 选择 "添加新项"。Select Add New Item.

在 "已安装的模板" 下,展开 C#视觉对象并选择WebUnder Installed Templates, expand Visual C# and select Web. 然后,在模板列表中,选择 " WEB API 控制器类"。Then, from the list of templates, select Web API Controller Class. 将控制器命名为 "ProductsController",然后单击 "添加"。Name the controller "ProductsController" and click Add.

"添加新项" 向导将创建一个名为 "ProductsController.cs" 的文件。The Add New Item wizard will create a file named ProductsController.cs. 删除向导包含的方法并添加以下方法:Delete the methods that the wizard included and add the following methods:

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));
        }
    }
}

有关此控制器中代码的详细信息,请参阅入门教程。For more information about the code in this controller, see the Getting Started tutorial.

添加路由信息Add Routing Information

接下来,我们将添加 URI 路由,以便将 "/api/products/" 格式的 Uri 路由到控制器。Next, we'll add a URI route so that URIs of the form "/api/products/" are routed to the controller.

解决方案资源管理器中,双击 "global.asax" 打开代码隐藏文件 Global.asax.cs。In Solution Explorer, double-click Global.asax to open the code-behind file Global.asax.cs. 添加以下using语句。Add the following using statement.

using System.Web.Http;

然后,将以下代码添加到应用程序_Start方法:Then add the following code to the Application_Start method:

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

有关路由表的详细信息,请参阅中的路由 ASP.NET Web APIFor more information about routing tables, see Routing in ASP.NET Web API.

添加客户端 AJAXAdd Client-Side AJAX

这就是创建客户端可以访问的 web API 所需的全部工作。That's all you need to create a web API that clients can access. 现在,让我们添加一个使用 jQuery 调用 API 的 HTML 页面。Now let's add an HTML page that uses jQuery to call the API.

请确保母版页(例如master)包含 ID="HeadContent"ContentPlaceHolderMake sure your master page (for example, Site.Master) includes a ContentPlaceHolder with ID="HeadContent":

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

打开文件 "default.aspx"。Open the file Default.aspx. 替换主要内容部分中的样本文本,如下所示:Replace the boilerplate text that is in the main content section, as shown:

<%@ 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 源文件的引用:Next, add a reference to the jQuery source file in the HeaderContent section:

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

注意:通过将文件从解决方案资源管理器拖放到代码编辑器窗口中,可以轻松地添加脚本引用。Note: You can easily add the script reference by dragging and dropping the file from Solution Explorer into the code editor window.

在 jQuery script 标记下面添加以下脚本块:Below the jQuery script tag, add the following script block:

<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>

加载文档时,此脚本将发出 AJAX 请求,"api/产品"。When the document loads, this script makes an AJAX request to "api/products". 请求返回 JSON 格式的产品列表。The request returns a list of products in JSON format. 该脚本将产品信息添加到 HTML 表中。The script adds the product information to the HTML table.

运行应用程序时,该应用程序应如下所示:When you run the application, it should look like this: