天天看點

【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;
        }
    });
});
           

轉載于:https://www.cnblogs.com/wangwust/p/6393186.html