创建包含CRUD操作的Web API接口2:实现Get方法
本节是前一节的延续,上一节中我们已经为我们的Web API项目创建必要的基础设施。
在本节中,我们将在我们的控制器类中实现操作方法,这些方法用来处理HTTP GET请求。
根据Web API命名约定,以“Get”开头的操作方法将用来处理HTTP Get请求。这个方法的名称可以直接叫“Get”,或者以“Get”开头。添加我们的第一个Action方法,给它一个名字GetAllStudents,因为它将从DB返回所有的学生信息。以一个适当的命名方法可以增加可读性,任何人都可以轻易理解方法的作用。
以下StudentController控制器(我们在上一节中创建)的GetAllStudents()操作方法使用实体框架从数据库中返回所有的学生。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public class StudentController : ApiController{ public IHttpActionResult GetAllStudents () { using (var ctx = new SchoolDBEntities()) { students = ctx.Students.Include("StudentAddress") .Select(s => new StudentViewModel() { Id = s.StudentID, FirstName = s.FirstName, LastName = s.LastName }).ToList<StudentViewModel>(); } if (students.Count == 0) { return NotFound(); } return Ok(students); }} |
正如你在上面的例子中所看到的,GetAllStudents()方法使用EF返回所有的学生。
如果DB中没有任何学生信息,那么它将返回404 NotFound响应,否则它将返回200 OK响应和学生数据。
ApiController中定义的NotFound()和Ok()用来返回响应码,分别为404和200。
在数据库中,每个学生都有0或1个地址。
假设,你想实现另一个方法来获取所有的学生的地址,你可以创建另一个GET方法如下所示。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
public class StudentController : ApiController{ public IHttpActionResult GetAllStudents () { using (var ctx = new SchoolDBEntities()) { students = ctx.Students.Include("StudentAddress") .Select(s => new StudentViewModel() { Id = s.StudentID, FirstName = s.FirstName, LastName = s.LastName }).ToList<StudentViewModel>(); } if (students.Count == 0) { return NotFound(); } return Ok(students); } public IHttpActionResult GetAllStudentsWithAddress() { IList<StudentViewModel> students = null; using (var ctx = new SchoolDBEntities()) { students = ctx.Students.Include("StudentAddress").Select(s => new StudentViewModel() { Id = s.StudentID, FirstName = s.FirstName, LastName = s.LastName, Address = s.StudentAddress == null ? null : new AddressViewModel() { StudentId = s.StudentAddress.StudentID, Address1 = s.StudentAddress.Address1, Address2 = s.StudentAddress.Address2, City = s.StudentAddress.City, State = s.StudentAddress.State } }).ToList<StudentViewModel>(); } if (students.Count == 0) { return NotFound(); } return Ok(students); }} |
上述web API示例编译没有错误,但是当你执行HTTP GET请求时就会回复以下发现多个操作错误。

这是因为你不能有多个操作方法拥有相同类型和相同数量的参数。以上两种操作方法都不包括任何参数。所以Web API不懂哪个方法执行HTTP GET请求http://localhost:64189/api/student。
下面的例子说明了如何处理这种情况。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
public class StudentController : ApiController{ public StudentController() { } public IHttpActionResult GetAllStudents(bool includeAddress = false) { IList<StudentViewModel> students = null; using (var ctx = new SchoolDBEntities()) { students = ctx.Students.Include("StudentAddress") .Select(s => new StudentViewModel() { Id = s.StudentID, FirstName = s.FirstName, LastName = s.LastName, Address = s.StudentAddress == null || includeAddress == false ? null : new AddressViewModel() { StudentId = s.StudentAddress.StudentID, Address1 = s.StudentAddress.Address1, Address2 = s.StudentAddress.Address2, City = s.StudentAddress.City, State = s.StudentAddress.State } }).ToList<StudentViewModel>(); } if (students.Count == 0) { return NotFound(); } return Ok(students); }} |
如您所见,GetAllStudents动作方法包括一个参数includeAddress,默认值为false。
如果HTTP请求在查询字符串中包含includeAddress参数的值为true,那么它将返回所有的学生并带上学生的地址信息否则它将返回学生但不会有地址信息。
例如,http://localhost:64189/api/student(64189是一个端口号,可以在你的环境中不同)将返回所有的学生信息不带地址信息如下所示。

一个HTTP请求http://localhost:64189/api/student?includeAddress=true将返回所有的学生及地址如下所示。

实现多个Get方法
如前所述,Web API控制器可以包括多个Get方法,但这些Get方法需要有不同的参数列表。
让我们添加以下Action方法StudentController演示Web API如何处理多个HTTP GET请求。
| Action方法 | 作用 |
| GetStudentById(int id) | 返回与id相匹配的学生信息 |
| GetAllStudents(string name) | 返回名称与name相匹配的学生列表 |
| GetAllStudentsInSameStandard(int standardId) | 返回指定标准的学生信息列表 |
下面是实现上述操作方法的示例。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
public class StudentController : ApiController{ public StudentController() { } public IHttpActionResult GetAllStudents(bool includeAddress = false) { IList<StudentViewModel> students = null; using (var ctx = new SchoolDBEntities()) { students = ctx.Students.Include("StudentAddress").Select(s => new StudentViewModel() { Id = s.StudentID, FirstName = s.FirstName, LastName = s.LastName, Address = s.StudentAddress == null || includeAddress == false ? null : new AddressViewModel() { StudentId = s.StudentAddress.StudentID, Address1 = s.StudentAddress.Address1, Address2 = s.StudentAddress.Address2, City = s.StudentAddress.City, State = s.StudentAddress.State } }).ToList<StudentViewModel>(); } if (students == null) { return NotFound(); } return Ok(students); } public IHttpActionResult GetStudentById(int id) { StudentViewModel student = null; using (var ctx = new SchoolDBEntities()) { student = ctx.Students.Include("StudentAddress") .Where(s => s.StudentID == id) .Select(s => new StudentViewModel() { Id = s.StudentID, FirstName = s.FirstName, LastName = s.LastName }).FirstOrDefault<StudentViewModel>(); } if (student == null) { return NotFound(); } return Ok(student); } public IHttpActionResult GetAllStudents(string name) { IList<StudentViewModel> students = null; using (var ctx = new SchoolDBEntities()) { students = ctx.Students.Include("StudentAddress") .Where(s => s.FirstName.ToLower() == name.ToLower()) .Select(s => new StudentViewModel() { Id = s.StudentID, FirstName = s.FirstName, LastName = s.LastName, Address = s.StudentAddress == null ? null : new AddressViewModel() { StudentId = s.StudentAddress.StudentID, Address1 = s.StudentAddress.Address1, Address2 = s.StudentAddress.Address2, City = s.StudentAddress.City, State = s.StudentAddress.State } }).ToList<StudentViewModel>(); } if (students.Count == 0) { return NotFound(); } return Ok(students); } public IHttpActionResult GetAllStudentsInSameStandard(int standardId) { IList<StudentViewModel> students = null; using (var ctx = new SchoolDBEntities()) { students = ctx.Students.Include("StudentAddress").Include("Standard").Where(s => s.StandardId == standardId) .Select(s => new StudentViewModel() { Id = s.StudentID, FirstName = s.FirstName, LastName = s.LastName, Address = s.StudentAddress == null ? null : new AddressViewModel() { StudentId = s.StudentAddress.StudentID, Address1 = s.StudentAddress.Address1, Address2 = s.StudentAddress.Address2, City = s.StudentAddress.City, State = s.StudentAddress.State }, Standard = new StandardViewModel() { StandardId = s.Standard.StandardId, Name = s.Standard.StandardName } }).ToList<StudentViewModel>(); } if (students.Count == 0) { return NotFound(); } return Ok(students); }} |
现在,上面的Web API将处理对应的HTTP GET请求。
| HTTP GET请求url | 描述 |
| http://localhost:64189/api/student | 返回所有学生的列表,没有相关地址。 |
| http://localhost:64189/api/student?includeAddress=false | 返回所有学生的列表,没有相关地址。 |
| http://localhost:64189/api/student?includeAddress=true | 返回所有学生的列表,包括地址。 |
| http://localhost:64189/api/student?id=123 | 返回指定id的学生信息 |
| http://localhost:64189/api/student?name=steve | 返回指定name的学生信息 |
| http://localhost:64189/api/student?standardId=5 | 返回指定standardid的学生列表 |
你可以用同样的方式来实现Get方法,用来处理Web API的不同的HTTP Get请求。
下面的图显示了Fiddler操作HTTP GET请求。

下图显示了Fidder中以上Http Get请求的响应结果。

接下来,我们将学习如何在Web API中实现Post操作方法来处理HTTP Post请求。
创建包含CRUD操作的Web API接口2:实现Get方法的更多相关文章
- 创建包含CRUD操作的Web API接口3:实现Post方法
本节是前面两节的延续,前面我们为Web API创建了必要的基础设施,并实现了Get方法.在这里,我们将在Web API中实现POST方法. 在RESTful架构中,使用HTTP POST请求用来在数据 ...
- 创建包含CRUD操作的Web API接口-第一部
在这里,我们将创建一个新的Web API项目,它将使用实体框架实现Get,POST.PUT和DELETE方法来实现CRUD操作. 首先,在Visual Studio 2013 for Web expr ...
- 创建包含CRUD操作的Web API接口5:实现Delete方法
本节是前面四节的延续,在前面几节中我们创建了Web API并添加了必要的基础设施,实现了Get.Post.和Put方法.本节中,我们将介绍如何在Web API中实现Delete方法. 在RESTful ...
- 创建包含CRUD操作的Web API接口4:实现Put方法
本节教程是前三节的延续,在前面我们创建了Web API和必要的基础设施,也实现了Get和Post方法.接下来,我们将在Web API中实现Put方法. RESTful架构中,HTTP PUT方法用于在 ...
- 【ASP.NET Web API教程】2.1 创建支持CRUD操作的Web API
原文 [ASP.NET Web API教程]2.1 创建支持CRUD操作的Web API 2.1 Creating a Web API that Supports CRUD Operations2.1 ...
- Http下的各种操作类.WebApi系列~通过HttpClient来调用Web Api接口
1.WebApi系列~通过HttpClient来调用Web Api接口 http://www.cnblogs.com/lori/p/4045413.html HttpClient使用详解(java版本 ...
- Web API接口设计经验总结
在Web API接口的开发过程中,我们可能会碰到各种各样的问题,我在前面两篇随笔<Web API应用架构在Winform混合框架中的应用(1)>.<Web API应用架构在Winfo ...
- Web API接口设计(学习)
1.在接口定义中确定MVC的GET或者POST方式 由于我们整个Web API平台是基于MVC的基础上进行的API开发,因此整个Web API的接口,在定义的时候,一般需要显示来声明接口是[HttpG ...
- 不使用jQuery对Web API接口POST,PUT,DELETE数据
前些天,Insus.NET有演示Web API接口的操作: <怎样操作WebAPI接口(显示数据)>http://www.cnblogs.com/insus/p/5670401.html ...
随机推荐
- SQL基础-创建新的输出字段
一.创建新的输出字段 1.建表.插数据 ### CREATE TABLE `t_stock_trans_dtl` ( `trans_id` varchar(100) NOT NULL COMMENT ...
- SQL基础-建表
一.建表 1.创建表的两种方式 *客户端工具 *SQL语句 2.使用SQL语句创建表 表名和字段名不能使用中文:(一般为字母开头,字母.数字.下划线组成的字符串): CREATE TABLE关键字后跟 ...
- javascript中的indexOf与if判断的装逼写法
常规indexOf与if判断写法: if("112233".indexOf("22")>-1) { console.log("很二") ...
- 安卓入门教程(十四)-菜单,ActionBar,对话框
已经发表个人公众号 菜单类型 选项菜单(OptionMenu) 子菜单(SubMenu) 上下文菜单(ContextMenu) 方法: public boolean onCreateOptionsMe ...
- Exception in thread "main" java.lang.IllegalStateException: Failed to read 问题解决
开发中偶尔遇到这样的问题:Exception in thread "main" java.lang.IllegalStateException: Failed to read .. ...
- hadoop作业
作业要求:https://edu.cnblogs.com/campus/gzcc/GZCC-16SE1/homework/3223 一.准备一个ubantu 系统 二.创建hadoop用户 创建 设密 ...
- AOP注解方式ApsectJ开发
AOP注解方式ApsectJ开发 引入配置文件 编写切面类配置 使用注解的AOP对象目标类进行增强 在配置文件中开启以注解形式进行AOP开发 在切面类上添加注解 注解AOP通知类型 @Before前置 ...
- (二)OpenCV-Python学习—对比度增强
·对于部分图像,会出现整体较暗或较亮的情况,这是由于图片的灰度值范围较小,即对比度低.实际应用中,通过绘制图片的灰度直方图,可以很明显的判断图片的灰度值分布,区分其对比度高低.对于对比度较低的图片,可 ...
- SymPy解方程的实现
https://www.cnblogs.com/zgyc/p/6277562.html SymPy完全是用Python写的,并不需要外部的库 原理: 单纯用语言内置的运算与变量解决的是,由值求结果.如 ...
- MXNet 定义新激活函数(Custom new activation function)
https://blog.csdn.net/weixin_34260991/article/details/87106463 这里使用比较简单的定义方式,只是在原有的激活函数调用中加入. 准备工作下载 ...