Post(新增),Put(修改),Delete(刪除),Get(查詢)javascript
GET:生到數據列表(默認),或者獲得一條實體數據java
POST:添加服務端添加一條記錄,記錄實體爲Form對象jquery
PUT:添加或修改服務端的一條記錄,記錄實體的Form對象,記錄主鍵以GET方式進行傳輸ajax
DELETE:刪除 服務端的一條記錄api
上面公開的API接口都是在XMLHttpRequest狀況下調用的,固然你可使用jquery的ajax組件來完成這個請求調用ide
<fieldset> <legend>測試Web Api </legend> <a href="javascript:add()">添加(post)</a> <a href="javascript:update(1)">更新(put)</a> <a href="javascript:deletes(1)">刪除(delete)</a> <a href="/api/test">列表(Get)</a> <a href="/api/test/1">實體(Get)</a> </fieldset> <script> function add() { $.ajax({ url : "/api/Test/", type : "POST", data :{"UserID":4,"UserName":"test","UserEmail":"Parry@cnblogs.com"}, success: function (data) { alert(JSON.stringify(data)); } }); } //更新 function update(id) { $.ajax({ url : "/api/Test?id="+id, type : "Put", data :{"UserID":1,"UserName":"moditest","UserEmail":"Parry@cnblogs.com"}, success: function (data) { alert(JSON.stringify(data)); } }); } function deletes(id) { $.ajax({ url : "/api/Test/1", type : "DELETE", success: function (data) { alert(data);} }); } </script>
/// <summary> /// Test模塊API /// URI:/Api/Test /// </summary> public class TestController : ApiController { /// <summary> /// User Data List /// </summary> private readonly List<Users> _userList = new List<Users> { new Users {UserID = 1, UserName = "zzl", UserEmail = "bfyxzls@sina.com"}, new Users {UserID = 2, UserName = "Spiderman", UserEmail = "Spiderman@cnblogs.com"}, new Users {UserID = 3, UserName = "Batman", UserEmail = "Batman@cnblogs.com"} }; /// <summary> /// 獲得列表對象 /// </summary> /// <returns></returns> public IEnumerable<Users> Get() { return _userList; } /// <summary> /// 獲得一個實體,根據主鍵 /// </summary> /// <param name="id"></param> /// <returns></returns> public Users Get(int id) { return _userList.FirstOrDefault(i => i.UserID == id); } /// <summary> /// 添加 /// </summary> /// <param name="form">表單對象,它是惟一的</param> /// <returns></returns> public Users Post([FromBody] Users entity) { _userList.Add(entity); return entity; } /// <summary> /// 更新 /// </summary> /// <param name="id">主鍵</param> /// <param name="form">表單對象,它是惟一的</param> /// <returns></returns> public Users Put(int id, [FromBody]Users entity) { var user = _userList.FirstOrDefault(i => i.UserID == id); if (user != null) { user.UserName = entity.UserName; user.UserEmail = entity.UserEmail; } return user; } /// <summary> /// 刪除 /// </summary> /// <param name="id">主鍵</param> /// <returns></returns> public void Delete(int id) { _userList.Remove(_userList.FirstOrDefault(i=>i.UserID==id)); } }