Web API 2 入门——使用Web API与ASP.NET Web窗体(谷歌翻译)
作者: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窗体应用程序。输入项目的名称,然后单击确定。
创建模型和控制器
本教程使用与入门教程相同的模型和控制器类。
首先,添加一个模型类。在解决方案资源管理器中,右键单击项目并选择添加类。命名产品类,并添加以下实现:
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的文件。删除向导包含的方法并添加以下方法:
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表中。
运行应用程序时,应该如下所示:

Web API 2 入门——使用Web API与ASP.NET Web窗体(谷歌翻译)的更多相关文章
- 【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 ...
- Asp.Net Core 实现谷歌翻译ApI 免费版
由于谷歌翻译官方API是付费版本,本着免费和开源的精神.分享一下用 Net Core 实现谷歌翻译API的代码. 项目引用的Nuget 包: ChakraCore.NET Newtonsoft.Jso ...
- 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 ...
- ASP.NET Web API系列教程目录
ASP.NET Web API系列教程目录 Introduction:What's This New Web API?引子:新的Web API是什么? Chapter 1: Getting Start ...
- Swagger 生成 ASP.NET Web API
使用 Swagger 生成 ASP.NET Web API 在线帮助测试文档 原文:ASP.NET Web API Help Pages using Swagger作者:Shayne Boyer翻译: ...
- ASP.NET Web API系列教程(目录)(转)
注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP.NET Web API.这是一个用来在.NET平台上建立HTTP服务的Web API框架,是微软的又一项令人振奋的技术.目前,国内 ...
- [转]ASP.NET Web API系列教程(目录)
本文转自:http://www.cnblogs.com/r01cn/archive/2012/11/11/2765432.html 注:微软随ASP.NET MVC 4一起还发布了一个框架,叫做ASP ...
- 杂项:ASP.NET Web API
ylbtech-杂项:ASP.NET Web API ASP.NET Web API 是一种框架,用于轻松构建可以访问多种客户端(包括浏览器和移动设备)的 HTTP 服务. ASP.NET Web A ...
- ASP.NET Web API 管道模型
ASP.NET Web API 管道模型 前言 ASP.NET Web API是一个独立的框架,也有着自己的一套消息处理管道,不管是在WebHost宿主环境还是在SelfHost宿主环境请求和响应都是 ...
- ASP.NET Web API 路由对象介绍
ASP.NET Web API 路由对象介绍 前言 在ASP.NET.ASP.NET MVC和ASP.NET Web API这些框架中都会发现有路由的身影,它们的原理都差不多,只不过在不同的环境下作了 ...
随机推荐
- Java线程问题(基础回顾)
1.概念:线程是运行程序(进程)中单个顺序的小程序,一个进程可以由多个线程组成,而这多个线程共享同一个存储空间,这使得线程间的通信比较容易.在一个多进程的程序中,如果要切换到另一个进程,需要改变地址空 ...
- 【随笔】nginx重启问题和mysql挂了的解决办法
租了一个阿里云服务器,然后需要一个nginx来处理一下静态文件的访问和动态文件的转发,头一天没有什么问题,第二次打开,各种问题就出来了!解决方法记录一下.... Can't connect to lo ...
- ubuntu系统之难
声明 笔者最近意外的发现 笔者的个人网站http://tiankonguse.com/ 的很多文章被其它网站转载,但是转载时未声明文章来源或参考自 http://tiankonguse.com/ 网站 ...
- idea 下 启动maven项目,mybatis报错 Error parsing SQL Mapper Configuration. Cause: java.io.IOException。。。。。
我的具体报错日志是 Error parsing SQL Mapper Configuration. Cause: java.io.IOException Could not find resou ...
- android去除标题栏
在 AndroidManifast.xml 文件中 将 theme="@style/AppTheme" 改为 theme="@style/Theme.AppCompat. ...
- Grunt:任务自动管理工具(收藏+转载)
原文:http://javascript.ruanyifeng.com/tool/grunt.html 安装 命令脚本文件Gruntfile.js Gruntfile.js实例:grunt-contr ...
- Js 合并 table 行 的实现方法
Js 合并 table 行 的实现方法 需求如下: 某公司的员工档案,如下, 经理看员工的信息不是很清晰: 姓名 所在学校 毕业时间 张三 小学 2000 张三 中学 2006 张三 大学 2010 ...
- ASP.NET能知道的东西
ASP.NET能知道的东西 获取服务器电脑名: Page.Server.ManchineName 获取用户信息: Page.User 获取客户端电脑名:Page.Request.UserHostNam ...
- 利用WebBrowser控件实现百度自动搜索
(1)新建一个MFC对话框项目 (2)对话框中添加WebBrower控件,添加方法:点击菜单栏工具->选择工具箱项->在弹出的选择工具箱项对话框选择COM组件->Microsoft ...
- mongodb操作之mongoose
/** * Created by chaozhou on 2015/10/6. */ var mongoose = require("mongoose"); var db = mo ...

