参考链接:http://www.cnblogs.com/lori/p/3555737.html
简单的了解到RESTful架构后,跟着以上链接做了一个小练习。
Step1:
新建WebApi项目,新建controller命名为TestController
在TestController中的代码如下:
public class TestController : ApiController
{
/// <summary>
/// User Data List
/// </summary> private readonly List<Users> _userList = new List<Users>
{
new Users{ UserID=,UserName="Admin",UserEmail="[email protected]"},
new Users {UserID = , UserName = "Spiderman", UserEmail = "[email protected]"},
new Users {UserID = , UserName = "Batman", UserEmail = "[email protected]"}
}; /// <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));
} }
Step2:
新建html页面,在html中代码如下:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="../../Scripts/jquery-1.10.2.min.js"></script>
<script src="../../Scripts/jquery-1.10.2.js"></script>
</head>
<body>
<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": , "UserName": "test", "UserEmail": "[email protected]" },
success: function (data) { alert(JSON.stringify(data)); }
});
} //更新
function update(id) {
$.ajax({
url: "/api/Test?id=" + id,
type: "Put",
data: { "UserID": , "UserName": "moditest", "UserEmail": "[email protected]" },
success: function (data) { alert(JSON.stringify(data)); }
});
}
function deletes(id) {
$.ajax({
url: "/api/Test/1",
type: "DELETE",
success: function (data) { alert(data); }
});
}
</script>
</body>
</html>
总结:
从练习中学习到RESTful标准相比较传统的webService方式,在前端提交到后台服务上,更加方便快捷,并且以上练习,让人很清晰可以根据以前掌握的ajax提交,只是改变了URL和type方式,其它的方式都更加亲切,所以更加的通俗易懂。