zoukankan      html  css  js  c++  java
  • 【ASP.NET MVC 学习笔记】- 20 ASP.NET Web API

    本文参考:http://www.cnblogs.com/willick/p/3441432.html

    1、ASP.NET Web API(本文简称Web API),是基于ASP.NET平台构建RESTful应用程序的框架。

    2、Web API基于在 MVC 应用程序中添加的一个特殊的 Controller,这种 Controller 称为 API Controller,和MVC普通的 Controller 相比它主要有如下两个不同的特点:

    • Action 方法返回的是 Model 对象,而不是ActionResult。
    • 在请求时,Action 方法是基于 HTTP 请求方式来选择的。

    3、从API Controller的Action方法返回给客户端的Model对象是经过JSON编码的。API Controller的设计仅是为了提供传递Web数据的服务,因此它不支持View、Layout 和其它HTML呈现相关的特性。Web API 能支持任何有Web 功能的客户端,但最常用的是为Web应用程序中的Ajax请求提供服务。

    4、一般我们会在下面这两种情况下选择使用API Controler:

    • 需要大量的返回JSON格式数据的Action方法。
    • 和HTML无关,只是纯粹为数据提供服务。

    5、API Controller示例:

    public class ReservationController : ApiController {
            IReservationRepository repo = ReservationRepository.getRepository();
    
            public IEnumerable<Reservation> GetAllReservations() {
                return repo.GetAll();
            }
    
            public Reservation GetReservation(int id) {
                return repo.Get(id);
            }
    
            public Reservation PostReservation(Reservation item) {
                return repo.Add(item);
            }
    
            public bool PutReservation(Reservation item) {
                return repo.Update(item);
            }
    
            public void DeleteReservation(int id) {
                repo.Remove(id);
            }
        }

        API Controller 在 /App_Start/WebApiConfig.cs 中有它们自己的路由配置,你可以打开该文件看看VS默认注册好的路由:

    public static void Register(HttpConfiguration config) {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    //默认的Web API路由有一个静态片段(api),还有controller和 id片段变量。和MVC路由一个关键不同点是,它没有action片段变量。 }

    6、当应用程序接收到一个和Web API 路由匹配的请求时,Action方法的调用将取决于发送HTTP请求的方式。当我们用 /api/reservation URL测试API Controller时,浏览器指定的是GET方式的请求。API Controller的基类 ApiController根据路由信息知道需要调用哪个Controller,并根据HTTP请求的方式寻找适合的Action方法。

        一般约定在Action方法前加上HTTP请求方式名作为前缀。这里前缀只是个约定,Web API能够匹配到任何包含了HTTP请求方式名的Action方法。也就是说,本文示例的GET请求将会匹配 GetAllReservations 和 GetReservation,也能够匹配 DoGetReservation 或 ThisIsTheGetAction。

        对于两个含有相同HTTP请求方式的Action方法,API Controlller会根据它们的参数和路由信息来寻找最佳的匹配。例如请求 /api/reservation URL,GetAllReservations 方法会被匹配,因为它没有参数;请求 /api/reservation/3 URL,GetReservation 方法会被匹配,因为该方法的参数名和URL的 /3 片段对应的片段变量名相同。我们还可以使用 POST、DELETE 和 PUT请求方式来指定ReservationController的其它Action方法。这就是前文提到的REST的风格。

        但有的时候为了用HTTP方式名来给Action方法命名会显得很不自然,比如 PutReservation,习惯上会用 UpdateReservation。不仅用PUT命名不自然,POST也是一样的。这时候就需要使用类似于MVC的Controller中使用的Action方法选择器了。在System.Web.Http 命名空间下同样包含了一系列用于指定HTTP请求方式的特性,如下所示:

    public class ReservationController : ApiController {
        ...
        [HttpPost]
        public Reservation CreateReservation(Reservation item) {
            return repo.Add(item);
        }
        [HttpPut]
        public bool UpdateReservation(Reservation item) {
            return repo.Update(item);
        } 
        ...
    }

    7、ApiController的调用:

    function selectView(view) { 
        $('.display').not('#' + view + "Display").hide(); 
        $('#' + view + "Display").show(); 
    } 
    function getData() { 
        $.ajax({ 
            type: "GET", 
            url: "/api/reservation", 
            success: function (data) { 
                $('#tableBody').empty(); 
                for (var i = 0; i < data.length; i++) { 
                    $('#tableBody').append('<tr><td><input id="id" name="id" type="radio"' 
                    + 'value="' + data[i].ReservationId + '" /></td>' 
                    + '<td>' + data[i].ClientName + '</td>' 
                    + '<td>' + data[i].Location + '</td></tr>'); 
                } 
                $('input:radio')[0].checked = "checked"; 
                selectView("summary"); 
            } 
        }); 
    } 
    $(document).ready(function () { 
        selectView("summary"); 
        getData(); 
        $("button").click(function (e) { 
            var selectedRadio = $('input:radio:checked') 
            switch (e.target.id) {
                case "refresh":
                    getData();
                    break;
                case "delete":
                    $.ajax({
                       type: "DELETE",
                       url: "/api/reservation/" + selectedRadio.attr('value'),
                   success: function (data) {
                         selectedRadio.closest('tr').remove();
                       }
                    });
                    break;
                case "add":
                    selectView("add");
                    break;
                case "edit":
                    $.ajax({
                         type: "GET",
                         url: "/api/reservation/" + selectedRadio.attr('value'),
                         success: function (data) {
                                $('#editReservationId').val(data.ReservationId);
                                $('#editClientName').val(data.ClientName);
                          $('#editLocation').val(data.Location);
                                selectView("edit");
                         }
                    });
                    break;
                case "submitEdit":
                    $.ajax({
                         type: "PUT",
                         url: "/api/reservation/" + selectedRadio.attr('value'),
                         data: $('#editForm').serialize(),
                          success: function (result) {
                                       if (result) {
                                          var cells = selectedRadio.closest('tr').children();
                                          cells[1].innerText = $('#editClientName').val();
                                          cells[2].innerText = $('#editLocation').val();
                                          selectView("summary");
                                       }
                          }
                    });
                    break;
            }
        });
    });
    
  • 相关阅读:
    Git 处理tag和branch的命令
    手把手教您使用第三方登录
    iOS 中隐藏UITableView最后一条分隔线
    Android简易实战教程--第四十四话《ScrollView和HorizontalScrollView简单使用》
    iOS-改变UITextField的Placeholder颜色的三种方式
    react-native 关闭黄屏警告
    reactnative js onclick 模拟单击/双击事件
    reactnative 监听屏幕方向变化
    reactnative0.61.2 使用react-native-webrtc
    use react-navigation@2.18.2
  • 原文地址:https://www.cnblogs.com/wangwust/p/6393186.html
Copyright © 2011-2022 走看看