最近学习了下WebApi,WebApi是RESTful风格,根据请求方式决定操作。以博客的形式写出来,加深印象以及方便以后查看和复习。
1、首先我们使用VS创建一个空的WebApi项目
2、新建实体以及控制器类
1 public class Product 2 { 3 public int Id { set; get; } 4 public string Name { set; get; } 5 public string Description { set; get; } 6 }
1 public class HomeController : ApiController 2 { 3 static List<Product> modelList = new List<Product>() 4 { 5 new Product(){Id=1,Name="电脑",Description="电器"}, 6 new Product(){Id=2,Name="冰箱",Description="电器"}, 7 }; 8 9 //获取所有数据 10 [HttpGet] 11 public List<Product> GetAll() 12 { 13 return modelList; 14 } 15 16 //获取一条数据 17 [HttpGet] 18 public Product GetOne(int id) 19 { 20 return modelList.FirstOrDefault(p => p.Id == id); 21 } 22 23 //新增 24 [HttpPost] 25 public bool PostNew(Product model) 26 { 27 modelList.Add(model); 28 return true; 29 } 30 31 //删除 32 [HttpDelete] 33 public bool Delete(int id) 34 { 35 return modelList.Remove(modelList.Find(p => p.Id == id)); 36 } 37 38 //更新 39 [HttpPut] 40 public bool PutOne(Product model) 41 { 42 Product editModel = modelList.Find(p => p.Id == model.Id); 43 editModel.Name = model.Name; 44 editModel.Description = model.Description; 45 return true; 46 } 47 }
3、新建html页面使用ajax操作
1 <!DOCTYPE html> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>Demo</title> 6 <script src="/Scripts/jquery-1.10.2.js"></script> 7 <script type="text/javascript"> 8 $(function () { 9 add(); 10 update(); 11 find(); 12 remove(); 13 getAll(); 14 }); 15 function getAll() { 16 $.ajax({ 17 url: "api/Home/", 18 type: ‘GET‘, 19 success: function (data) { 20 console.log(data); 21 } 22 }); 23 } 24 25 function find() { 26 $.ajax({ 27 url: "api/Home/1", 28 type: ‘GET‘, 29 success: function (data) { 30 console.log(data); 31 } 32 }); 33 } 34 35 function add() { 36 $.ajax({ 37 url: "api/Home/", 38 type: "POST", 39 data: { "Id": "3", "Name": "电磁炉", "Description": "电器" }, 40 success: function (data) { 41 console.log(data); 42 } 43 }); 44 45 } 46 47 function update() { 48 $.ajax({ 49 url: "api/Home/", 50 type: ‘PUT‘, 51 data: { "id": "1", "Name": "洗衣机", "Description": "家具" }, 52 success: function (data) { 53 console.log(data); 54 } 55 }); 56 } 57 58 function remove() { 59 $.ajax({ 60 url: "api/Home/1", 61 type: ‘DELETE‘, 62 success: function (data) { 63 console.log(data); 64 } 65 }); 66 } 67 </script> 68 </head> 69 <body> 70 <h1>WebApi基本操作</h1> 71 </body> 72 </html>
4、通过开发人员工具可以看到如下
WebApi默认是以XML格式返回,但是一般我们需要返回Json,通过在Global.asax里的Application_Start方法中加上如下代码可以移除XML,让其只返回Json
GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
时间: 2024-10-10 03:37:13