做者:Mike Wassonjavascript
虽然ASP.NET Web API与ASP.NET MVC打包在一块儿,但很容易将Web API添加到传统的ASP.NET Web窗体应用程序中。本教程将引导您完成步骤。html
概观
要在Web窗体应用程序中使用Web API,有两个主要步骤:java
- 添加从ApiController类派生的Web API控制器。
- 向Application_Start方法添加路由表。
建立Web窗体项目
启动Visual Studio并从“ 开始”页面选择“ 新建项目 ” 。或者,从文件菜单中选择新建,而后选择项目。jquery
在“ 模板”窗格中,选择“ 已安装的模板”并展开Visual C#节点。在Visual C#下,选择Web。在项目模板列表中,选择ASP.NET Web窗体应用程序。输入项目的名称,而后单击肯定。git
2github
建立模型和控制器
本教程使用与入门教程相同的模型和控制器类。web
首先,添加一个模型类。在解决方案资源管理器中,右键单击项目并选择添加类。命名产品类,并添加如下实现:ajax
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请求的对象。api
在解决方案资源管理器中,右键单击项目。选择添加新项目。app
在已安装的模板下,展开Visual C#并选择Web。而后,从模板列表中选择Web API Controller Class。命名控制器“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中的路由。
添加客户端AJAX
这就是建立一个客户端能够访问的Web API所须要的。如今咱们来添加一个使用jQuery调用API的HTML页面。
打开文件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.7.1.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/>', { text: row }) // Append the name. .appendTo($('#products')); }); }); } $(document).ready(getProducts); </script>
当文档加载时,此脚本会向“api / products”发出AJAX请求。该请求返回JSON格式的产品列表。该脚本将产品信息添加到HTML表中。
运行应用程序时,应该以下所示: