我仍在学习 Web API,所以如果我的问题听起来很愚蠢,请原谅我。
我的里面有这个StudentController
:
public HttpResponseMessage PostStudent([FromBody]Models.Student student)
{
if (DBManager.createStudent(student) != null)
return Request.CreateResponse(HttpStatusCode.Created, student);
else
return Request.CreateResponse(HttpStatusCode.BadRequest, student);
}
为了测试这是否有效,我使用 Google Chrome 的扩展“Postman”来构建 HTTP POST 请求来测试它。
这是我的原始 POST 请求:
POST /api/Student HTTP/1.1
Host: localhost:1118
Content-Type: application/json
Cache-Control: no-cache
{"student": [{"name":"John Doe", "age":18, "country":"United States of America"}]}
student
应该是一个对象,但是当我调试应用程序时,API 收到student
对象但内容始终是null
.
FromBody 是一个奇怪的属性,因为当参数不是基本类型时,输入 POST 值需要采用特定格式才能使参数非空。 (这里是学生)
- 尝试您的请求
{"name":"John Doe", "age":18, "country":"United States of America"}
作为 json。
- 去除
[FromBody]
属性并尝试解决方案。它应该适用于非原始类型。 (学生)
- 随着
[FromBody]
属性,另一个选项是将值发送到=Value
格式,而不是key=value
格式。这意味着您的关键价值是student
应该是一个空字符串...
还有其他选项可以为学生班级编写自定义模型绑定程序,并使用自定义绑定程序赋予参数属性。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)