一、RESTful和Web API
Representational State Transfer (REST) is a software architecture style consisting of guidelines and best practices for creating scalable web services. REST is a coordinated set of constraints applied to the design of components in a distributed hypermdedia system that can lead to a more performant and maintainable architecture. -- wikipedia
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.
原來RESTful是一種軟件架構風格(REST是一種設計風格,而不是一種標准),而ASP.NET Web API是其在.NET平台的一種標准/實現。目前在三種主流的Web Services實現方案中,因為REST模式與復雜的SOAP和XML -PRC相比更加簡潔,越來越多的web服務開始采用REST風格設計和實現。
ASP.NET整體框架結構如下圖。可以看出,Web API支持JSON和XML,面向的是多種客戶終端,包括多瀏覽器和各種移動設備。

二、簡單示例
新建ASP.NET Web Application,命名NBAApp

選擇Empty模板,下面選擇Web API,更改Authentication為No Authentication

新建一個Model - Player
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace NBAApp.Models { public class Player { public int Id { get; set; } public int No { get; set; } public string Name { get; set; } public string Position { get; set; } public string Team { get; set; } } }
新建Controller - PlayersController,模板選擇Web API 2 Controller - Empty

編輯代碼如下
using NBAApp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace NBAApp.Controllers { public class PlayersController : ApiController { Player[] players = new Player[] { new Player { Id = 1, No = 3, Name = "Chris Paul", Position = "Point Guard", Team = "Los Angeles Clippers" }, new Player { Id = 2, No = 3, Name = "Dwyane Wade", Position = "Shooting Guard", Team = "Miami Heat" }, new Player { Id = 3, No = 23, Name = "LeBron James", Position = "Forward", Team = "Cleveland Cavaliers" }, new Player { Id = 4, No = 21, Name = "Tim Duncan", Position = "Power forward", Team = "San Antonio Spurs" }, new Player { Id = 5, No = 33, Name = "Marc Gasol", Position = "Center", Team = "Memphis Grizzlies" } }; public IEnumerable<Player> GetAllPlayers() { return players; } public IHttpActionResult GetPlayer(int id) { var player = players.FirstOrDefault<Player>(p => p.Id == id); if (player == null) { return NotFound(); } return Ok(player); } } }
添加Html - Index.html頁面

編輯代碼如下
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>NBA App</title> </head> <body> <div> <h2>All Players</h2> <ul id="players" /> </div> <div> <h2>Search by ID</h2> <input type="text" id="prodId" size="5" /> <input type="button" value="Search" onclick="find();" /> <p id="player" /> </div> <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script> <script> var uri = 'api/players'; $(document).ready(function () { // Send an AJAX request $.getJSON(uri) .done(function (data) { // On success, 'data' contains a list of players. $.each(data, function (key, item) { // Add a list item for the player. $('<li>', { text: formatItem(item) }).appendTo($('#players')); }); }); }); function formatItem(item) { return item.Id + ": " + item.Name + "(" + item.No + ')' + " - " + item.Team + "(" + item.Position + ")"; } function find() { var id = $('#prodId').val(); $.getJSON(uri + '/' + id) .done(function (data) { $('#player').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#player').text('Error: ' + err); }); } </script> </body> </html>
執行效果如下(Chrome瀏覽器)

F12調出Developer Tools,點擊紅點Recording Network Log,刷新頁面,結果如下

點擊進去,並選擇Response標簽,可以清楚地看到傳輸交換的是JSON格式的字符

代碼下載
