HTTP 不仅仅服务于 web 页面。同一时候也是构建暴露服务和数据的 API 的强大平台。HTTP 有着简单、灵活和无处不在的特点。你能想到的差点儿全部平台都包括有一个 HTTP 库。所以 HTTP 服务能够遍及广泛的 client,包括浏览器、移动设备和传统桌面应用程序。
ASP.NET Web API 是一个在. NET 框架上构建 web API 的框架。在本教程中,你将使用 ASP.NET Web API 来创建一个返回产品列表的 web API。
在本教程中,你将使用 ASP.NET Web API 来创建一个返回产品列表的 web API。
前端页面使用 jQuery 来显示结果。
开启 Visual Studio 并在開始页面选择 New Project。或者在 File 目录下选择 New。然后选择 Project。
在 Template 面板中,选择 Installed Templates。然后展开 Visual C# 节点。
在 Visual C# 节点下。选择 Web。
在项目模板列表中。选择 ASP.NET Web Application。
命名项目为 "ProductsApp" 并点击 OK。
在 NEW ASP.NET Project 对话框中,选择 Empty 模板。在 "Add folders and core references for",选中 Web API。点击 OK。
凝视:你也能够用 "Web API" 模板来创建 Web API。
Web API 模板使用了 ASP.NET MVC 来提供 API 的帮助页面。我在本教程中使用 Empty 模板是由于我希望不用 MVC 来展示 Web API。通常,你不必了解 ASP.NET MVC 就能使用 Web API。
模型是在你的应用程序中表示数据的对象。
ASP.NET Web API 能够将你的模型自己主动序列化成 JSON、XML 或其它格式。然后将其序列化数据写入到 HTTP 响应消息的 body 中。
仅仅要 client 能够读取序列化格式,它就能够反序列化出对象。
差点儿全部 client 都能解析 XML 或 JSON。并且。client 还能通过在 HTTP 请求的 Accept header 中设置来指明它想要的格式。
让我们来创建一个表示产品的简单模型吧。
假设 Solution Explorer 没有显示出来,点击 View 菜单,然后选择 Solution Explorer。在 Solution Explorer 中。右击 Models 目录。从上下文菜单中选择 Add。然后选择 Class。
命名该类为 "Product"。加入下面属性到 Product 类中。
- namespace ProductsApp.Models {
- public class Product {
- public int Id {
- get;
- set;
- }
- public string Name {
- get;
- set;
- }
- public string Category {
- get;
- set;
- }
- public decimal Price {
- get;
- set;
- }
- }
- }
在 Web API 中,控制器(controller)是处理 HTTP 请求的对象。
我们将加入一个能够依据 ID 来返回多个或一个产品的控制器。
备注:假设你还没有使用过 ASP.NET MVC,你应该已经对控制器非常熟悉了。Web API 的控制器和 MVC 的控制器非常相近。可是它继承的是 ApiController 而不是 Controller。
在 Solution Explorer 中,右击 Controllers 目录。选择 Add,然后选择 Controller。
在 Add Scaffold 对话框中,选择 Web API Controller – Empty。
点击 Add。
在 Add Controller 对话框,给控制器命名为 "ProductsController"。
点击 Add。
接下来便会在 Controllers 目录下创建一个名为 ProductsController.cs 的文件。
备注:事实上你不必非得把控制器加入到 Controllers 目录下。目录名称仅仅是为了更方便你组织源文件。
假设文件没有打开,那就双击文件打开它。在文件里替换成下面代码:
- using ProductsApp.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Web.Http;
- namespace ProductsApp.Controllers {
- 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 IHttpActionResult GetProduct(int id) {
- var product = products.FirstOrDefault((p) = >p.Id == id);
- if (product == null) {
- return NotFound();
- }
- return Ok(product);
- }
- }
- }
为了让演示样例简单化,products 被存储在控制器类中的固定数组中。当然,在实际应用程序中,你可能想要查询数据库或使用其它外部数据源。
控制器定义了两个返回产品的方法:
1. GetAllProducts 方法将整个产品列表作为 IEnumerable 类型返回。
2. GetProduct 方法通过它的 ID 来查找单个产品。
没错,你已经有一个能够使用的 web API 了。控制器上的每一个方法都相应一个或多个 URI:
Controlle Method | URI |
---|---|
GetAllProducts | /api/products |
GetProduct | /api/products/id |
对于 GetProduct 方法,URI 中的 id 是一个占位符。比如。为了得到一个 ID 为 5 的产品,URI 是 api/products/5。
在本节中,我们将加入一个使用 AJAX 来调用 Web API 的 html 页面。我们将使用 jQuery 来产生 AJAX 调用并用返回结果来更新页面。
在 Solution Explorer 中,右击项目并选择 Add,然后选择 New Item。
在 Add New Item 对话框中,选择 Visual C# 下的 Web 节点,然后选择 HTML Page 选项。
命名页面为 "index.html"。
用下面代码替换文件里的全部:
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title>
- Product App
- </title>
- </head>
- <body>
- <div>
- <h2>
- All Products
- </h2>
- <ul id="products" />
- </div>
- <div>
- <h2>
- Search by ID
- </h2>
- <input type="text" id="prodId" size="5" />
- <input type="button" value="Search" onclick="find();" />
- <p id="product" />
- </div>
- <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js">
- </script>
- <script>
- var uri = 'api / products';
- $(document).ready(function() {
- // Send an AJAX request
- $.getJSON(uri).done(function(data) {
- // On success, 'data' contains a list of products.
- $.each(data,
- function(key, item) {
- // Add a list item for the product.
- $(' < li > ', {
- text: formatItem(item)
- }).appendTo($('#products'));
- });
- });
- });
- function formatItem(item) {
- return item.Name + ': $' + item.Price;
- }
- function find() {
- var id = $('#prodId').val();
- $.getJSON(uri + ' / ' + id).done(function(data) {
- $('#product').text(formatItem(data));
- }).fail(function(jqXHR, textStatus, err) {
- $('#product').text('Error: ' + err);
- });
- }
- </script>
- </body>
- </html>
有好几个方法去得到 jQuery。在本例中,我使用 Microsoft Ajax CDN。你也能够在 http://jquery.com / 下载它。让 ASP.NET "Web API" 项目包括 jQuery。
为了得到 Products 列表。能够发送一个 HTTP 的 GET 请求到 "/api/products"。
jQuery 的 getJSON 函数会发送 AJAX 请求。
当中包括了 JSON 对象数组。done 函数指定了一个当请求成功时触发的回调。在回调中。我们用产品信息更新 DOM。
- $(document).ready(function() {
- // Send an AJAX request
- $.getJSON(apiUrl).done(function(data) {
- // On success, 'data' contains a list of products.
- $.each(data,
- function(key, item) {
- // Add a list item for the product.
- $(' < li > ', {
- text: formatItem(item)
- }).appendTo($('#products'));
- });
- });
- });
假设想要通过 ID 来取得产品,能够发送 HTTP 的 GET 请求到 "/api/products/id",当中 id 就是产品的 ID。
- function find() {
- var id = $('#prodId').val();
- $.getJSON(apiUrl + ' / ' + id).done(function(data) {
- $('#product').text(formatItem(data));
- }).fail(function(jqXHR, textStatus, err) {
- $('#product').text('Error: ' + err);
- });
- }
我们仍然使用 getJSON 来发送 AJAX 请求,可是这次我们将 ID 放到 URI 请求中。它的响应会是一个代表了单个产品的 JSON 对象。
按 F5 開始调试应用程序,web 页面看起来会是下面这样:
为了通过 ID 获得产品,输入 ID 并点击 Search。
假设你输入了一个无效的 ID,那么 server 就会返回 HTTP 错误消息。
当你工作于 HTTP 服务时,假设能够查看 HTTP 请求和响应的具体无疑是非常有帮助的。
你能够在 IE9 中使用 F12 开发人员工具来做这些操作。在 IE9 中,按 F12 来打开工具。点击 Network 面板,并点击 Start Capturing。如今返回到 web 页面,并按 F5 来又一次载入 web 页面。
IE 将会捕捉到浏览器和 webserver 之间的 HTTP 传输。下图显示了一个页面的全部 HTTP 传输。
定位到相对 URI"api/products/"。选中并点击 Go to detailed view。
在具体视图中,这里多个面板用于查看请求和响应的 header 和 body。
比如。假设你点击 Request headers,你就会看到 client 在 Accept header 请求了 "application/json"。
假设你点击了 Response body,你就会看到产品列表怎样被序列化成 JSON。其它浏览器也有类似的功能。还有一个实用的工具是 Fiddler,它是一个 web 调试代理工具。你能够使用 Fiddler 来查看 HTTP 传输,也能够合成 HTTP 请求,后者能够给予你在请求上对于 HTTP 头部的全然控制。
来源: http://www.bubuko.com/infodetail-2164185.html