一 什么是WebAPI
- web:网页
- API:接口(一套别人封装的属性和方法)
- webAPI:专门操作网页的方法和属性
万物皆对象,在webAPI中把网页中所有元素都当成对象来处理
二 Restful
- 在REST规则中,有两个基础概念:对象、行为
- 对象就是我们要操作的对象,例如添加用户的操作,那么对象就是user
- 行为有4种常用的:查看、创建、编辑、删除
- rest的提出者很巧妙的利用http现有方法来对应这4种行为:
GET - 查看
POST - 创建
PUT - 编辑
DELETE - 删除
三 学习Dome
public class Students
{
public int Id { get; set; }
public string Name { get; set; }
}
public class StudentsController : ApiController
{
public List<Students> Get() {
return new List<Students>() {
new Students{ Id=1,Name="zhangsan1"},
new Students{ Id=2,Name="zhangsan2"},
new Students{ Id=3,Name="zhangsan3"},
new Students{ Id=4,Name="zhangsan4"},
new Students{ Id=5,Name="zhangsan5"},
};
}
public string Get(String name)
{
return "你传入的参数是" + name;
}
public void Post(Students stu)
{
throw new Exception("错了");
}
public void Put(int Id,Students stu) {
}
public void Delete(int id) {
}
}
//get请求返回data数据
$.ajax({
url: "/api/Students?name=白晨星",
type: "get"
}).done(function (data) {
console.log(data);
})
//post请求给存值
$.ajax({
url: "/api/Students",
type: "post",
data: {
Id:1,
Name:"wangwu"
}
}).done(function () {
console.log("成功")
}).fail(function () {
console.log("失败")
})
//put请求通过Id修改值
$.ajax({
url: "/api/Students/1",
type: "Put",
data: {
Id: 12,
Name:"白晨星"
}
})
//delete请求通过Id删除数据
$.ajax({
url: "/api/students/1",
type: "delete",
})
四 自定义
public class User
{
public string Admin { get; set; }
public string Pwd { get; set; }
}
public class UserController : ApiController
{
[HttpPost]//没有用restful风格,需要自己定制用那种类型来处理
[Route("Login")]
public string Login(User user)
{
return "OK";
}
[HttpGet]
[Route("Message")]
public IHttpActionResult GetMessage() {
//ok 200 //成功
//notfound 404
//InternalServerError 500 服务器错误
// return InternalServerError(new Exception("nicuo l "));
return Ok(new Students()
{
Id = 80,
Name = "及格了"
});
}
}
//根据自定义的url给服务器传data数据 验证登录账号和密码
$.ajax({
url: "/api/User/Login",
type: "post",
data: {
Admin: "admin",
Pwd:"123456"
}
})
$.ajax({
url: "/api/User/Message",
type: "get",
}).done(function (data) {
console.log("成功了",data)
})