[.NET WebAPI系列01] WebAPI 简单例子

【源】

  来自微软WebAPI官方视频,Introduction to the ASP.NET Web API --Uniform Interface -- Demo-Using convention 这一节。

  http://pluralsight.com/training/Player?author=jon-flanders&name=aspnetwebapi-m1-introduction&mode=live&clip=0&course=aspnetwebapi

      先上一张WebAPI中所有用户Controller都必须继承的ApiController基类代码:

  

【详】

  1.VS 2012中新建一MVC4的WebAPI项目;

      2.添加CoursesController空WebAPI控制器,代码如下: 

 1 namespace WebApiDemo.Controllers
 2 {
 3     public class course
 4     {
 5         public int id;
 6         public string title;
 7     }
 8     public class CoursesController : ApiController
 9     {
10         static List<course> courses = InitCourses();
11         private static List<course> InitCourses()
12         {
13             var ret = new List<course>();
14             ret.Add(new course { id = 0, title = "Web Api" });
15             ret.Add(new course { id = 1, title = "Mobile programing" });
16             return ret;
17         }
18           
19         public IEnumerable<course> Get()
20         {
21             return courses;
22         }
23         
24     }
25 }

  3.在HomeView中呈现:

  更改/Views/Home/Index.cshtml代码,使其和下面代码相同;

 1 <div id="body">
 2     <ol id="courses">
 3 
 4     </ol>
 5 </div>
 6 @section scripts
 7 {
 8     <script>
 9         $.ajax({
10             url: '/api/courses',
11             success: function (courses) {
12                 var list = $('#courses');
13                 for (var i = 0; i < courses.length; i++)
14                 {
15                     var course = courses[i];
16                     list.append('<li>' + course.title + '</li>');
17                 }
18             }
19 
20         });
21     </script>
22  }

  注意:

    1) 原理:用jQuery代码,指定要访问的url是coursescontroller所在uri,从而获取courses的json数据;

        如果获取成功,执行success后代码,通过循环将li添加到指定的ol中。

    2)ol标签的id必须为courses,和下面$('#courses')中的相同,否则挂不上;

       url、success等关键字也不能写错,否则运行不出,而且jQuery错误比较难查。

【果】

  最终效果:

  

 【update】
  上面紧紧展示了GETALL的用法,CRUD补全后的Controller如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Net;
 5 using System.Net.Http;
 6 using System.Web.Http;
 7 
 8 namespace WebApiDemo.Controllers
 9 {
10     public class course
11     {
12         public int id;
13         public string title;
14     }
15     public class CoursesController : ApiController
16     {
17         static List<course> courses = InitCourses();
18         private static List<course> InitCourses()
19         {
20             var ret = new List<course>();
21             ret.Add(new course { id = 0, title = "Web Api" });
22             ret.Add(new course { id = 1, title = "Mobile programing" });
23             return ret;
24         }
25         
26         // GET api/courses
27         public IEnumerable<course> Get()
28         {
29             return courses;
30         }
31        
32         // GET api/courses/id
33         public course Get(int id)
34         { 
35             var ret=(from c in courses
36                      where c.id==id
37                      select c).FirstOrDefault();
38             //todo: if null- should return 404
39             return ret;
40         }
41 
42         // Post api/courses
43         public void Post([FromBody]course c)
44         {
45             c.id = courses.Count;
46             courses.Add(c);
47             //TODO:: should return a 201 with a location head
48 
49         }
50 
51         // Put api/courses/id
52         public void Put(int id, [FromBody]course c)
53         {
54             var ret = (from v in courses
55                        where v.id == c.id
56                        select v).FirstOrDefault();
57             ret.title = c.title;
58         }
59 
60         // Delete api/courses/id
61         public void Delete(int id)
62         {
63             var ret = (from c in courses
64                        where c.id == id
65                        select c).FirstOrDefault();
66             courses.Remove(ret);
67         }
68     }
69 }

  在此就不再为每个方法创建视图了,如果想要测试结果,可以使用视频中推荐的"Fiddler Web Debugger",官网:fiddler2.com

  另外,如果不想使用Get、Put、Delete、Post作为WebApi Controller CRUD的方法名,就需要在自定义方法明前标注Attribute:

  • C :[HttpPost]
  • R  : [HttpGet]
  • U  : [HttpPut]
  • D  : [HttpDelete]

  如:

1 // GET api/courses
2         [HttpGet]
3         public IEnumerable<course> AllCourses()
4         {
5             return courses;
6         }

 【知识点解析】

  1.WebAPi Controller 方法参数中的[FromBody]&[FromUri],称为ModleBinding attribute

   参数前缀修饰,用来指定参数值的来源。

   FromBody:指示当前参数来源自HTML 的Body中,body只能被读取一次;

   FromUri:指示当前参数来源于URL,比如QuerryString。

   被修饰的参数,就不需要再给形参赋值,

   WebAPI会自动将URI或HTTP Body中符合要求的数据绑定到方法中

原文地址:https://www.cnblogs.com/chutianshu1981/p/3288796.html