web-api POST 主体对象始终为空 [英] web-api POST body object always null
问题描述
我仍在学习 Web API,如果我的问题听起来很愚蠢,请原谅我.
I'm still learning web API, so pardon me if my question sounds stupid.
我的 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 请求来测试它.
In order to test if this is working, I'm using Google Chrome's extension "Postman" to construct the HTTP POST request to test it out.
这是我的原始 POST 请求:
This is my raw POST request:
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
.
student
is supposed to be an object, but when I debug the application, the API receives the student
object but the content is always null
.
推荐答案
FromBody 是一个奇怪的属性,当它不是原始类型时,输入 POST 值需要采用特定格式才能使参数为非空类型.(学生在这里)
FromBody is a strange attribute in that the input POST values need to be in a specific format for the parameter to be non-null, when it is not a primitive type. (student here)
- 尝试使用
{"name":"John Doe", "age":18, "country":"United States of America"}
作为 json 的请求. - 删除
[FromBody]
属性并尝试解决方案.它应该适用于非原始类型.(学生) - 使用
[FromBody]
属性,另一个选项是以=Value
格式发送值,而不是key=value
格式.这意味着您的student
键值应该是一个空字符串...
- Try your request with
{"name":"John Doe", "age":18, "country":"United States of America"}
as the json. - Remove the
[FromBody]
attribute and try the solution. It should work for non-primitive types. (student) - With the
[FromBody]
attribute, the other option is to send the values in=Value
format, rather thankey=value
format. This would mean your key value ofstudent
should be an empty string...
还有其他选项可以为学生类编写自定义模型绑定器,并使用自定义绑定器属性参数.
There are also other options to write a custom model binder for the student class and attribute the parameter with your custom binder.
这篇关于web-api POST 主体对象始终为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!