web api可以提供方便简单可靠的web服务,可以大量的用于不需要提供复杂的soap协议的环境,以简单明了的形式返回数据,在不太复杂的环境中web api可以做为wcf等重级web服务的一种可替代方案
在web世界中常常使用的方法有
GET
Post
PUT
DELETE
在controler中通常约定,方法名以以上get,post,put,delete打头,相关的请求将根据路由规则自动匹配相应的处理方式,如果需要自定义方法名,不希望以GET.Post,Put,Delete等来做为方法名的一部分,需要以在方法前加特性说做说明,如
[HttpGet]
[HttpPost]
[HttpPut]
[HttpDelete]
Views对于WebAPI来说没有太大的用途,Models中的Model主要用于保存Service和Client交互的对象,这些对象默认情况下会被转换为Json格式的数据进行传输,Controllers中的Controller对应于WebService来说是一个Resource,用于提供服务。和普通的MVC一样,Global.asax用于配置路由规则
以下为具体后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using webapi.Models;
namespace webapi.Controllers
{
public class UserController : ApiController
{
public static List<UserInfo> allModeList = new List<UserInfo>() {
new UserInfo(){ id=1,userName="zhang", password="123"},
new UserInfo(){ id=2,userName="lishi", password="123456"},
new UserInfo(){ id=3,userName="wang", password="1234567"}
};
public IEnumerable<UserInfo> getAll()
{
return allModeList;
}
[HttpGet]
public UserInfo findById(int id)
{
return allModeList.Find(p => p.id == id);
}
public bool PostNew(UserInfo user)
{
try
{
allModeList.Add(user);
return true;
}
catch (Exception)
{
return false;
}
}
[HttpDelete]
public bool RemoveAll()
{
return allModeList.RemoveAll(p=>p.id!=-1) > 0;
}
[HttpDelete]
public bool RemoveItemById(int id)
{
return allModeList.Remove(allModeList.Find(p => p.id == id));
}
public UserInfo getUserByName(string username)
{
return allModeList.Find(p => p.userName == username);
}
[HttpPut]
public void updateById(int id,UserInfo model)
{
UserInfo userInfoItem = allModeList.Find(p=>p.id==id);
allModeList.Remove(userInfoItem);
userInfoItem.userName = model.userName;
userInfoItem.password = model.password;
allModeList.Add(userInfoItem);
}
}
}
前台代码:
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
function getAll() {
$.ajax({
url: "/api/User/",
type: 'GET',
success: function (data) {
document.getElementById("modes").innerHTML = ""
$.each(data, function (key, val) {
str = val.id + ": " + val.userName + " : " + val.password
$('<li/>', { html: str }).appendTo($('#modes'))
console.log(key)
})
}
}).fail(function (xhr, textStatus, err) {
alert('error'+err)
})
}
function find() {
$.ajax({
url: '/api/User/1',
type: 'GET',
success: function (data) {
document.getElementById("modes").innerHTML = ""
str = data.userName + " : " + data.password
$('<li/>', { html: str }).appendTo($('#modes'))
}
}).fail(function (xhr, textstatus, err) {
alert('Error Info'+err)
})
}
function add() {
$.ajax({
url: "/api/user/",
type: "POST",
dataType: "json",
data: { 'id': 4, 'userName': 'test1', 'password': 'Pass@word' },
success: function (data) {
getAll()
}
}).fail(function (xhr, textstatus, err) {
alert("error"+err)
})
}
function removeAll()
{
$.ajax({
url: '/api/user/',
type: 'DELETE',
success: function (data) {
getAll()
}
}).fail(function (xhr,textstatus,err) {
alert('error'+err)
})
}
function removeUser() {
$.ajax({
url: '/api/user/1',
type: 'DELETE',
success: function (data) {
getAll()
}
}).fail(function (xhr, textstatus, err) {
alert("error"+err)
})
}
function getUserByName()
{
$.ajax({
url: '/api/user?username=zhang',
type: 'GET',
success: function (data) {
str=data.userName+": "+data.password
$('<li/>', { html: str }).appendTo($('#modes'))
console.log(data)
}
})
}
function udpate()
{
$.ajax({
url: '/api/user/2',
type: 'PUT',
dataType: 'json',
data: { Id: 2, "userName": "admin", "password": "666666" },
success: function (data) {
getAll()
}
}).fail(function (xhr, textstatus, err) {
alert('error'+err)
})
}
</script>
</head>
<body>
<div>
<button οnclick="getAll()">getAll</button>
<button οnclick="find()">find</button>
<button οnclick="add()">add</button>
<button οnclick="removeUser()">remove</button>
<button οnclick="removeAll()">removeAll</button>
<button οnclick="udpate()">udpate</button>
<button οnclick="getUserByName()">getUserByName</button>
</div>
<div id="modes">
</div>
</body>
</html>
运行结果 :