作者:Mike Wasson

虽然ASP.NET Web API与ASP.NET MVC打包在一起,但很容易将Web API添加到传统的ASP.NET Web窗体应用程序中。本教程将引导您完成步骤。

概观

要在Web窗体应用程序中使用Web API,有两个主要步骤:

  • 添加从ApiController类派生的Web API控制器。
  • 向Application_Start方法添加路由表。

创建Web窗体项目

启动Visual Studio并从“ 开始”页面选择“ 新建项目 ” 。或者,从文件菜单中选择新建,然后选择项目。

在“ 模板”窗格中,选择“ 已安装的模板”并展开Visual C#节点。在Visual C#下,选择Web。在项目模板列表中,选择ASP.NET Web窗体应用程序。输入项目的名称,然后单击确定。

2

创建模型和控制器

本教程使用与入门教程相同的模型和控制器类。

首先,添加一个模型类。在解决方案资源管理器中,右键单击项目并选择添加类。命名产品类,并添加以下实现:

C#复制
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 Controller Class。命名控制器“ProductsController”,然后单击添加。

“ 添加新项目”向导将创建一个名为ProductsController.cs的文件。删除向导包含的方法并添加以下方法:

C#复制
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语句。

C#复制
using System.Web.Http;

然后将以下代码添加到Application_Start方法中:

C#复制
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。更换主内容部分中的样板文本,如图所示:

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源文件的引用:

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

注意:您可以通过将解决方案资源管理器中的文件拖放到代码编辑器窗口中来轻松添加脚本引用。

1

在jQuery脚本标记下面添加以下脚本块:

HTML复制
<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表中。

运行应用程序时,应该如下所示:

 

Web API 2 入门——使用Web API与ASP.NET Web窗体(谷歌翻译)的更多相关文章

  1. 【ASP.NET Web API教程】1.1 第一个ASP.NET Web API

    Your First ASP.NET Web API (C#)第一个ASP.NET Web API(C#) By Mike Wasson|January 21, 2012作者:Mike Wasson ...

  2. Asp.Net Core 实现谷歌翻译ApI 免费版

    由于谷歌翻译官方API是付费版本,本着免费和开源的精神.分享一下用 Net Core 实现谷歌翻译API的代码. 项目引用的Nuget 包: ChakraCore.NET Newtonsoft.Jso ...

  3. ASP.Net Web API 输出缓存 转载 -- Output caching in ASP.NET Web API

    一.Nuget安装相关dll Web API 2 : Install-Package Strathweb.CacheOutput.WebApi2 Web API 1 : Install-Package ...

  4. ASP.NET Web API系列教程目录

    ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...

  5. Swagger 生成 ASP.NET Web API

    使用 Swagger 生成 ASP.NET Web API 在线帮助测试文档 原文:ASP.NET Web API Help Pages using Swagger作者:Shayne Boyer翻译: ...

  6. ASP.NET Web API系列教程(目录)(转)

    注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内 ...

  7. [转]ASP.NET Web API系列教程(目录)

    本文转自:http://www.cnblogs.com/r01cn/archive/2012/11/11/2765432.html 注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP ...

  8. 杂项:ASP.NET Web API

    ylbtech-杂项:ASP.NET Web API ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务. ASP.NET Web A ...

  9. ASP.NET Web API 管道模型

    ASP.NET Web API 管道模型 前言 ASP.NET Web API是一个独立的框架,也有着自己的一套消息处理管道,不管是在WebHost宿主环境还是在SelfHost宿主环境请求和响应都是 ...

  10. ASP.NET Web API 路由对象介绍

    ASP.NET Web API 路由对象介绍 前言 在ASP.NET.ASP.NET MVC和ASP.NET Web API这些框架中都会发现有路由的身影,它们的原理都差不多,只不过在不同的环境下作了 ...

随机推荐

  1. WinScp结合Putty在Windows与UNIX之间进行文件传输

    1. 关于传输协议: SSH Secure Shell安全外壳协议 SFTP Secure File Transfer Protocal安全文件传送协议 2. WinScp与Putty的作用: Put ...

  2. SQL Server 2005 中的分区表和索引

    SQL Server 2005 中的分区表和索引 SQL Server 2005          69(共 83)对本文的评价是有帮助 - 评价此主题   发布日期 : 3/24/2005 | 更新 ...

  3. document.referrer的使用和window.opener 跟 window.parent 的区别

    偶尔看到了document.referrer,之前一直有点疑惑与window.opener 和 window.parent之间的区别 首先查了一下w3cSCHOOL, 上面的解释:referrer 属 ...

  4. Ubuntu 下常用的命令 简略记录

    # 动态显示 NVIDIA watch -n 1 nvidia-smi #查看某一目录下文件的总数(不包含子目录) ls -l | wc -l #挂载硬盘或者U盘 mount /dev/sdb1 /m ...

  5. 关于80286——《x86汇编语言:从实模式到保护模式》读书笔记15

    一.80286的工作模式 80286首次提出了实模式和保护模式的概念. 实模式:和8086的工作方式相同: 保护模式:提供了存储器管理机制和保护机制,支持多任务. 二.80286的寄存器 (一)通用寄 ...

  6. 解决MysqlWorkbench Export Data时报错:'delayed-insert'=FALSE

  7. [转].NET Core dotnet 命令大全

    本文转自:http://www.cnblogs.com/linezero/p/dotnet.html https://docs.microsoft.com/en-us/dotnet/articles/ ...

  8. [转] 多种方法查看Oracle SQL执行计划

    本文转自:http://falchion.iteye.com/blog/616234 一.在线查看执行计划表 如果PLAN_TABLE表不存在,执行$ORACLE_HOME/rdbms/admin/u ...

  9. golang学习之闭包

    匿名函数不能够独立存在,但可以被赋值于某个变量,即保存函数的地址到变量中:fplus := func(x, y int) int { return x + y },然后通过变量名对函数进行调用:fpl ...

  10. [javaEE] EL表达式调用java方法

    1.新建个类,类里面定义静态方法 package com.tsh.utils; import java.net.URLEncoder; public class ELFunc { public sta ...