• 第一个 ASP.NET Web API应用程序


          HTTP 不只是用于生成 web 页面。它也是功能强大的平台,用于构建公开服务和数据的 Api。HTTP 是简单、灵活并且无处不在。所以 HTTP 客户端服务范围非常广泛,包括浏览器、 移动设备和传统的桌面应用程序。ASP.NET Web API 是用于生成 web Api 在.NET 框架上的框架。在本教程中,您将使用 ASP.NET Web API 创建的 web API 返回的产品列表。前端 web 页使用 jQuery 来显示结果。

    启动 Visual Studio 时,从开始页中选择新项目或者,从文件菜单中,选择新建,然后项目.

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

    新的 ASP.NET MVC 4 项目对话框中,选择Web API并单击确定.

    添加Model

    一个Model对象,表示您的应用程序中的数据模型ASP.NET Web API 可以自动序列化到 JSON、 XML 或一些其他格式,然后将序列化的数据写入 HTTP 响应消息的正文。只要客户端可以读取序列化格式,它可以反序列化对象。大多数客户端可以解析 XML 或 JSON。让我们首先创建一个简单的Model,此示例中用来代表一种产品。如果解决方案资源管理器中不可见,请单击视图菜单,然后选择解决方案资源管理器在解决方案资源管理器中,右键单击模型文件夹。从上下文菜单中,选择添加,然后选择.

    命名类"Product"。下一步,将下列属性添加到 Product类。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    
    namespace HellowWebApi.Models
    {
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Category { get; set; }
            public decimal Price { get; set; }
        } 
    
    }

         控制器是一个对象,用于处理 HTTP 请求。如果您使用过 ASP.NET MVC ,然后您已熟悉控制器。那么同样应用在Web API 中,但是Web API 中的控制器从ApiController类而不是控制器类派生的。还有一个主要区别是 Web API 控制器上的行动返回不是视图,而是返回数据。

      

    添加一个新的控制器,如下所示:

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

     

    添加控制器向导中,命名为"ProductsController"的控制器。模板下拉列表中选择空 API 控制器然后单击添加.

    添加控制器向导将创建一个名为控制器文件夹中的 ProductsController.cs 文件。

    添加下面的实现:

    using HellowWebApi.Models;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Http;
    using System.Web.Mvc;
    
    namespace HellowWebApi.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 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));
            } 
    
    
        }
    }

    这只是一个简单的模拟实现,控制器类内部使用固定数组来模拟数据存储产品。当然,在实际的应用程序,将从数据库中查询或使用一些其他外部数据源。

    控制器定义返回产品清单的三种方法:

    • GetAllProducts方法 返回IEnumerable <Product>类型的产品的整个列表。
    • GetProductById方法 根据产品Id查找一个单一的产品。
    • GetProductsByCategory方法 返回与指定类别的所有产品。

     每个控制器上的方法映射到一个 URI:

    控制器的方法URI
    GetAllProducts /api/products
    GetProductById /api/products/id
    GetProductsByCategory /api/products/?category=category

    客户端可以调用该方法,通过发送一个 HTTP GET 请求的 uri。稍后,我们来看看这种映射如何完成的。首先,让我们试试看。

    使用浏览器调用 Web API

     打开浏览器 输入http://localhost:xxxx/api/products/(替换"xxxx"为实际的端口数目。)

    具体的结果取决于您所使用的 web 浏览器。Ie 浏览器将提示您打开或保存一个名为Product的"文件".

    "文件",实际上就是 HTTP 响应的正文。单击打开。在打开方式对话框中选择记事本。单击确定,出现提示时,单击打开。该文件应包含数组的产品 JSON 表示形式:

     在Mozilla Firefox,将显示为 XML 格式在浏览器中。

    差异的理由是 Ie 和火狐浏览器发送标头接受不同,因此 web API 在响应中发送不同的内容类型。

    可以尝试请求浏览到这些 Uri:
    •http://localhost:xxxx/api/products/1
    •http://localhost:xxxx/api/products?category=hardware

    第一次应返回的条目 id 等于 1。第二个应回到"硬件"所有类别的产品平等的列表,(在本例中,单个项目)。

    使用Javascript 和 jQuery 调用 Web API

         在前一节中,我们调用直接从浏览器请求的 web API。但大部分的 web Api由客户端应用程序以编程方式使用。所以让我们写一个简单的 javascript 客户端。在解决方案资源管理器中,展开视图文件夹中。双击以打开一个名为 Index.cshtml 的文件。

    Index.cshtml使用razor 视图引擎呈现,本例中我们不使用任何的razor 语法,我们使用纯html和javascript的方式。

    将文本修改为以下内容:

    <!DOCTYPE html> 
    <html lang="en"> 
    <head> 
        <title>ASP.NET Web API</title> 
        <link href="http://www.cnblogs.com/Content/Site.css" rel="stylesheet" /> 
        <script src="http://www.cnblogs.com/Scripts/jquery-1.7.1.min.js" type="text/javascript"> 
            // TODO Add script 
        </script> 
    </head> 
    <body id="body" > 
        <div class="main-content"> 
            <div> 
                <h1>All Products</h1> 
                <ul id="products"/> 
            </div> 
            <div> 
                <label for="prodId">ID:</label> 
                <input type="text" id="prodId" size="5"/> 
                <input type="button" value="Search" onclick="find();" /> 
                <p id="product" /> 
            </div> 
        </div> 
    </body> 
    </html>

    获取产品的列表
    若要获取产品的列表,"api/products"发送一个 HTTP GET 请求。您可以使用 jQuery,如下所示:

    <script type="text/javascript"> 
        $(document).ready(function () { 
            // Send an AJAX request 
            $.getJSON("api/products/", 
            function (data) { 
                // On success, 'data' contains a list of products. 
                $.each(data, function (key, val) { 
     
                    // Format the text to display. 
                    var str = val.Name + ': $' + val.Price; 
     
                    // Add a list item for the product. 
                    $('<li/>', { text: str })     
                    .appendTo($('#products'));    
                }); 
            }); 
        }); 
    </script>

    GetJSON函数发送 AJAX 请求。响应将是 JSON 对象的数组。GetJSON的第二个参数是一个请求成功完成时调用的回调函数。

    获取产品 Id

    若要获取产品按 ID,将发送到 HTTP GET 请求"/id",其中id是产品 id。将下面的代码添加到该脚本块:

    function find() { 
        var id = $('#prodId').val(); 
        $.getJSON("api/products/" + id, 
            function (data) { 
                var str = data.Name + ': $' + data.Price; 
                $('#product').text(str); 
            }) 
        .fail( 
            function (jqXHR, textStatus, err) { 
                $('#product').text('Error: ' + err);  
            }); 
    }            

    下面的代码显示完整的 Index.cshtml 文件:

    <!DOCTYPE html> 
    <html lang="en"> 
    <head> 
        <title>ASP.NET Web API</title> 
        <link href="http://www.cnblogs.com/Content/Site.css" rel="stylesheet" /> 
        <script src="http://www.cnblogs.com/Scripts/jquery-1.7.1.min.js"  
            type="text/javascript"></script> 
     
            <script type="text/javascript"> 
                $(document).ready(function () { 
                    // Send an AJAX request 
                    $.getJSON("api/products/", 
                    function (data) { 
                        // On success, 'data' contains a list of products. 
                        $.each(data, function (key, val) { 
     
                            // Format the text to display. 
                            var str = val.Name + ': $' + val.Price; 
     
                            // Add a list item for the product. 
                            $('<li/>', { text: str }) 
                            .appendTo($('#products')); 
                        }); 
                    }); 
                }); 
     
                function find() { 
                    var id = $('#prodId').val(); 
                    $.getJSON("api/products/" + id, 
                        function (data) { 
                            var str = data.Name + ': $' + data.Price; 
                            $('#product').text(str); 
                        }) 
                    .fail( 
                        function (jqXHR, textStatus, err) { 
                            $('#product').text('Error: ' + err); 
                        }); 
                } 
            </script> 
     
    </head> 
    <body id="body" > 
        <div class="main-content"> 
            <div> 
                <h1>All Products</h1> 
                <ul id="products"/> 
            </div> 
            <div> 
                <label for="prodId">ID:</label> 
                <input type="text" id="prodId" size="5"/> 
                <input type="button" value="Search" onclick="find();" /> 
                <p id="product" /> 
            </div> 
        </div> 
    </body> 
    </html>

    运行应用程序

     按 f5 键以启动调试应用程序。在 web 页应如下所示:

    详情请参考: http://www.asp.net/web-api/

  • 相关阅读:
    如何挖掘需求,覆盖整个系统
    JVM全整理
    7.linux文件与目录管理
    6.linux的文件权限与目录配置
    获取外汇基本汇率
    Pointer-Events: 如何处理ScreenTouch和MouseClicks
    Excel如何快速定位出两列的不同值
    Java数据结构: java.util.BitSet源码学习
    一道面试题与Java位操作 和 BitSet 库的使用
    Test post.
  • 原文地址:https://www.cnblogs.com/suizhouqiwei/p/2735149.html
Copyright © 2020-2023  润新知