1.1ASP.NET Web API 2入门

HTTP 不只是为了生成 web 页面。它也是建立公开服务和数据的 Api 的强大平台。HTTP 是简单的、 灵活的和无处不在。你能想到的几乎任何平台有 HTTP 库,因此,HTTP 服务可以达到范围广泛的客户,包括浏览器、 移动设备和传统的桌面应用程序。

ASP.NET Web API 是用于生成 web Api 的一个基于.NET的框架。在本教程中,您将使用 ASP.NET Web API 来创建 web API 返回的产品列表。

在本教程中使用的软件版本

  • VS2015
  • Web API 2

一、创建一个WebApi的项目

在本教程中,您将使用 ASP.NET Web API 来创建返回的产品列表。前端的 web 页中使用 jQuery 来显示结果。

启动VS2015,文件--》新建项目

模板窗格中,选择已安装的模板和展开Visual C#节点。Visual C#,选择Web在项目模板的列表中,选择ASP.NET Web 应用程序命名该项目"ProductsApp"并单击确定.

在新建Asp.Net项目对话框中,选中Empty模版,在“为以下添加文件夹和核心引用”,勾选WebApi,单击确定。

稍等片刻,项目就创建好了。您还可以创建一个 Web API 项目使用"Web API"模板。Web API 模板使用 ASP.NET MVC 提供 API 的帮助页。我在本教程中使用空模板,因为我想要在没有MVC的情况下使用Web API。一般情况下,你不需要知道 ASP.NET MVC 使用了 Web API。

二、添加一个实体模型

实体是一个对象,表示应用程序中的数据。ASP.NET Web API 可以自动序列化 JSON,XML,或一些其他格式,您的模型,然后将序列化的数据写入到 HTTP 响应消息的正文。只要客户端可以读取序列化格式,它可以反序列化的对象。大多数客户端可以解析 XML 或 JSON。此外,客户端可以表明哪一种格式它希望通过在 HTTP 请求消息中设置 Accept 标头。

让我们开始创建一个简单的模型,它代表一种产品。

如果解决方案资源管理器看不见,请单击视图菜单中,选择解决方案资源管理器

在解决方案资源管理器中,右键单击模型文件夹。从上下文菜单中,选择添加,然后选择类。

将类命名为Product,添加一些属性:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ProductApp.Models
 8 {
 9     public class Product
10     {
11         public int Id { get; set; }
12         public string Name { get; set; }
13         public string Category { get; set; }
14         public decimal Price { get; set; }
15     }
16 }

三、创建控制器

在 Web API 中,控制器一个处理 HTTP 请求的对象。我们将添加一个控制器,可以返回的产品列表或一个单一的产品 ID 指定的

注意如果你使用了 ASP.NET MVC,您控制器已经熟悉了。Web API 控制器类似于 MVC 控制器,但是继承ApiController类而不是控制器类。

解决方案资源管理器中,右键单击控制器文件夹。选择添加,然后选择控制器.

添加基架对话框中,选择Web API 控制器-空单击添加.

添加控制器对话框中,名称"ProductsController"控制器。单击添加.

我们看到创建一个名为控制器文件夹中的 ProductsController.cs 文件。

注意:你不需要把您的控制器放进一个文件夹命名为控制器。文件夹名称是只是方便的方式来组织您的源文件。

接下来,在打开控制器,把代码替换成以下的内容

 1 using ProductApp.Models;
 2 using System;
 3 using System.Collections.Generic;
 4 using System.Linq;
 5 using System.Net;
 6 using System.Net.Http;
 7 using System.Web.Http;
 8 
 9 namespace ProductApp.Controllers
10 {
11     public class ProductsController : ApiController
12     {
13 
14         Product[] products = new Product[]
15        {
16             new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
17             new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
18             new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
19        };
20         public IEnumerable<Product> GetAllProducts()
21         {
22             return products;
23         }
24 
25         public IHttpActionResult GetProduct(int id)
26         {
27             var product = products.FirstOrDefault((p) => p.Id == id);
28             if (product == null)
29             {
30                 return NotFound();
31             }
32             return Ok(product);
33         }
34     }
35 }

为了保持示例简单,产品存储在一个固定的数组,在控制器类中。当然,在实际的应用中,你会查询数据库,或使用一些其他外部数据源。

控制器定义返回的产品的两种方法 ︰

  • GetAllProducts方法返回整个清单上的产品作为IEnumerable < 产品 >类型。
  • GetProduct方法查找一个单一的产品,由其 id。

就是这个 !你有工作 web API。每个控制器上的方法对应于一个或多个 Uri:

GetProduct方法,URI 中的id是一个占位符。例如,若要获取 id 为 5 的产品,URI 是api/products/5.

有关 Web API 如何将 HTTP 请求路由到控制器方法的详细信息,请参阅路由选择在 ASP.NET Web API.

四、用JavaScript和Jquery调用WebApi

在本节中,我们将添加一个 HTML 页面,使用 AJAX 调用 web API。我们将使用 jQuery,以使 AJAX 调用,用结果更新该页面。

在解决方案资源管理器中,右键单击该项目并选择添加,然后选择新项目.

把Html页面命名为index.html,把文件内容替换成以下内容:

 1 <!DOCTYPE html>
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4     <title>Product App</title>
 5 </head>
 6 <body>
 7 
 8     <div>
 9         <h2>All Products</h2>
10         <ul id="products" />
11     </div>
12     <div>
13         <h2>Search by ID</h2>
14         <input type="text" id="prodId" size="5" />
15         <input type="button" value="Search" onclick="find();" />
16         <p id="product" />
17     </div>
18 
19     <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
20     <script>
21     var uri = 'api/products';
22 
23     $(document).ready(function () {
24       // Send an AJAX request
25       $.getJSON(uri)
26           .done(function (data) {
27             // On success, 'data' contains a list of products.
28             $.each(data, function (key, item) {
29               // Add a list item for the product.
30               $('<li>', { text: formatItem(item) }).appendTo($('#products'));
31             });
32           });
33     });
34 
35     function formatItem(item) {
36       return item.Name + ': $' + item.Price;
37     }
38 
39     function find() {
40       var id = $('#prodId').val();
41       $.getJSON(uri + '/' + id)
42           .done(function (data) {
43             $('#product').text(formatItem(data));
44           })
45           .fail(function (jqXHR, textStatus, err) {
46             $('#product').text('Error: ' + err);
47           });
48     }
49     </script>
50 </body>
51 </html>

有多种方法来得到 jQuery。在此示例中,我使用Microsoft Ajax CDN您也可以下载它从http://jquery.com/和 ASP.NET"Web API"项目模板包括 jQuery 一样好。

获取产品列表:

若要获取产品的列表,向"/api/产品"发送一个 HTTP GET 请求。

JQuery getJSON函数发送一个 AJAX 请求。为响应包含的 JSON 对象的数组。done功能指定如果请求成功,则调用的回调。在回调中,我们使用的产品信息更新 DOM。

 1 $(document).ready(function () {
 2     // Send an AJAX request
 3     $.getJSON(apiUrl)
 4         .done(function (data) {
 5             // On success, 'data' contains a list of products.
 6             $.each(data, function (key, item) {
 7                 // Add a list item for the product.
 8                 $('<li>', { text: formatItem(item) }).appendTo($('#products'));
 9             });
10         });
11 });

获得产品的 ID

若要获取产品的 ID,发送 HTTP GET 请求"api/id",其中id是产品 id。

 1 function find() {
 2     var id = $('#prodId').val();
 3     $.getJSON(apiUrl + '/' + id)
 4         .done(function (data) {
 5             $('#product').text(formatItem(data));
 6         })
 7         .fail(function (jqXHR, textStatus, err) {
 8             $('#product').text('Error: ' + err);
 9         });
10 }

我们仍然叫getJSON发送 AJAX 请求,但这次我们把 ID 请求 URI 中。来自此请求的响应是产品的一个单一一个 JSON 表示。

五、运行程序

原文地址:https://www.cnblogs.com/duyao/p/5431204.html