网络API POST主体对象总是空 [英] web-api POST body object always null

查看:231
本文介绍了网络API POST主体对象总是空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还在学习网络的API,如果我的问题听起来很愚蠢,所以原谅我。

I'm still learning web-api, so pardon me if my question sounds stupid.

我有这在我的StudentController

I have this in my 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);
        }

为了测试是否这是工作,我使用谷歌Chrome浏览器的扩展名邮差构建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"}]}

学生应该是一个对象,但是当我调试应用程序,该API接收了学生对象,但内容始终是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)


  1. 尝试与您的要求{名:李四,时代:18日,国:美利坚合众国} 作为JSON 。

  2. 删除FromBody属性,并尝试解决方案。它应该工作的非原始类型。 (学生)

  3. 随着FromBody属性的另一种选择是发送值 =值格式,而不是的key = value 格式。这将意味着你的核心价值学生应该是一个空字符串...

  1. Try your request with {"name":"John Doe", "age":18, "country":"United States of America"} as the json.
  2. Remove the FromBody attribute and try the solution. It should work for non-primitive types. (student)
  3. With the FromBody attribute, the other option is to send the values in =Value format, rather than key=value format. This would mean your key value of student 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.

这篇关于网络API POST主体对象总是空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆