• Web Api初试


    前言

      ASP.NET Web API 与之前的内建HTTP服务解决方案的不同之处在于,它一开始就是围绕HTTP协议及其消息语义构建起来的。与WCF REST或ASP.NET AJAX加ASMX相比,它不是对现有框架的增强,而是一个全新的平台。新的ASP.NET Web API的优势在于它汇集了之前各平台的各种最佳特性,结合为一个全面而不臃肿的HTTP平台。这套Web API基于ASP.NET,又借用了很多ASP.NET MVC的概念,应该很容易被ASP.NET的开发者适应和熟悉。ASP.NET Web API有一些核心功能,能让它成为ASP.NET MVC框架现用户的自然选择,同时也切合HTTP端点开发者的需要。

    • 完善支持URL路由,透过用户熟悉的MVC风格路由语义,生成干净的URL
    • 根据Accept标头对请求和响应的序列化形式进行内容协商(Content Negotiation)
    • 支持大量输出格式,包括JSON、XML、ATOM等
    • 默认对REST语义有完善支持,同时又不强制限定必须使用REST语义
    • 易于扩展的Formatter机制,支持添加新的输入/输出类型
    • 可通过HttpResponseMessage类、HttpRequestMessage类和强类型枚举来描述大量的HTTP操作,提供对更高级的HTTP特性的深度支持
    • 基于惯例的设计引导用户按HTTP Services的正确方式行事
    • Formatters和Filters延续了MVC的扩展模型,具备出色的扩展能力
    • 用于非Web程序时,可以脱离IIS运行(Self-hostable)
    • 具备可测试性,测试机制的设计类似于MVC

    以上文字出自 Richard Seroter 的《微软随.NET 4.5发布新REST API框架》一文,本人初次接触WEB API,所以此次试着写了一个简单的例子。

    1、创建Asp.net web api解决方案,添加mvc4项目中的web api模板

    2、创建Model

      创建一个应用程序需要的model类,在http响应过程中web api可以自动将其序列化为xml,json或者其他数据类型,同时也可以在客户端接收响应的时候指定http头来实现我们想要接收的数据类型。

    在models文件夹下添加Customer实体:

    public class Customer
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Designation { get; set; }
            public decimal Salary { get; set; }
        }

    3、添加ApiController

    在控制器文件夹下有2个默认的controller,一个是普通的,一个是apicontroller,添加一个CustomersController来继承ApiController,然后添加如下方法:

    //
            // 数据源
            Customer[] customers = new Customer[] 
            { 
                new Customer { Id = 1, Name = "张三", Designation = "程序员", Salary = 50000 }, 
                new Customer { Id = 2, Name = "李四", Designation = "人事", Salary = 40000 }, 
                new Customer { Id = 3, Name = "田鸡", Designation = "后勤", Salary = 15000 } ,
                new Customer { Id = 4, Name = "刘风", Designation = "副总", Salary = 55000 } ,
                new Customer { Id = 5, Name = "程侯", Designation = "项目经理", Salary = 60000 } 
            };
            //返回所有的人员
            public IEnumerable<Customer> GetCustomers()
            {
                return customers;
            }
            //根据id查询
            public Customer GetCustomerById(int id)
            {
                var customer = customers.FirstOrDefault((p) => p.Id == id);
                if (customer == null)
                {
                    throw new HttpResponseException(HttpStatusCode.NotFound);
                }
                return customer;
            }
            //根据职位查询
            public IEnumerable<Customer> GetCustomersByDesignation(string designation)
            {
                if (!string.IsNullOrEmpty(designation))
                {
                    return customers.Where(
                        p => p.Designation.Contains(designation));
                }
                return customers;
            }

    根据默认的api路由规则可以得出action和uri如下对应规则:

    路由:

        public static class WebApiConfig
        {
            public static void Register(HttpConfiguration config)
            {
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: new { id = RouteParameter.Optional }
                );
            }
        }
    action uri
    GetCustomers /api/customers
    GetCustomerById /api/customers/id
    GetCustomersByDesignation /api/customers/?designation=des

    下面在浏览器中分别请求以上三个方法查看返回值:

    http://localhost:xxxx/api/customers:

    http://localhost:60764/api/customers/1:

    http://localhost:60764/api/customers/?designation=%E5%90%8E%E5%8B%A4:

    下面通过jquery实现下面效果:

    在index页面中添加如下代码:

    <div id="body">
        <div class="main-content">
            <div>
                <h1>所有成员</h1>
                <ul id="customers">
                </ul>
            </div>
            <div>
                <label for="custId">ID:</label>
                <input type="text" id="custId" size="5" />
                <input type="button" value="Search" onclick="findById();" />
                <br />
                <label for="designationValue">Designation:</label>
                <input type="text" id="designationValue" size="5" />
                <input type="button" value="Search" onclick="findByDesignation();" />
    
                <div id="customer" />
                <ul id="customersByDesignation">
                </ul>
            </div>
        </div>
    </div>

    通过jquery.ajax请求填充数据:

        <script type="text/javascript">
            $(function () {
                //获取所有人员
                $.getJSON("/api/customers", function (data) {
                    $.each(data, function (i,val) {
                        $("#customers").append("<li>" + val.Name + "</li>");
                    })
                })
            })
            //根据id搜索
            function findById() {
                var id = $('#custId').val();
                $.getJSON("/api/customers/" + id,function (data) {
                        var str = data.Name + ': $' + data.Salary;
                        $('#customer').text(str);
                    })
                .fail(
                    function (jqXHR, textStatus, err) {
                        $('#customer').text('Error: ' + err);
                    });
            }
            //根据职位描述搜索
            function findByDesignation() {
                var strDv = $('#designationValue').val();
                var table = '<table><tr  style=font-weight:bold><th>Name</td><td>Salary</th></tr>'
                $.getJSON("api/customers?designation=" + strDv, function (data) {
                    $.each(data, function (key, val) {
                        var str = val.Name + ': $' + val.Salary;
                        table = table + '<tr><td>' + val.Name + '</td><td>' + val.Salary + '</td></tr>'
                    });
                    table = table + '</table>';
                    $('#customer').html(table);
    
                })
                .fail(
                    function (jqXHR, textStatus, err) {
                        $('#customer').text('Error: ' + err);
                    });
            }
        </script>

    很简单代码不做过多的说明了。

    第一次使用mvc4中的新东西,没有深入使用,以此做个记号标记入门。

  • 相关阅读:
    NC_35_EDIT_COST NC_36_findMedianinTwoSortedAray NC_37_MERGEINTERVAL
    NC_18_ROTATEMATRIXNC_19_maxsumofSubarrayNC_20_restoreIpAddresses
    NC_22_MERGE_ARRAYNC_23_PARTITION_LISTNC_24_DELETEDUPLICATENODE
    NC_31_FirstNotRepeatingChar NC_32_SQRT NC_33_MERGE_LINKLIST NC_34_UNIQUE_PATH
    NC_49_longestValidParentheses NC_50_REVERSE_K_GROUP NC_51_Merge_KLists
    NC_45_THREE_ORDERS NC_46_TARGET_VALUE
    [学习笔记]最小割树
    [学习笔记]2SAT
    matlab gui界面按钮的回调函数名
    Qt中通过代码设置控件的objectName,和通过objectName查找该控件
  • 原文地址:https://www.cnblogs.com/flykai/p/3277517.html
Copyright © 2020-2023  润新知