一个简单的webAPI调用

1.新建一个ASP.NET Web应用程序。

2.选择空模板,WebAPI。

3.在Models文件夹添加Product类。

4.添加空控制器ProductController。

5.ProductController控制器添加下面代码。

6.添加一个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="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
20     <script>
21         var uri = 'api/Product';
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>
HTML

7.运行效果:

具体来自于微软官方:https://docs.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

猜你喜欢

转载自www.cnblogs.com/Zhengxue/p/9008458.html