【问题标题】:Why getting null in the request parameter为什么在请求参数中获取 null
【发布时间】:2017-08-24 00:09:44
【问题描述】:

下面是我的 API。

public HttpResponseMessage Delete(IEnumerable<int> customerIds)
{
    //api stuff
}

但是当这个 API 被点击时,我将 customerIds 设为 null。

这就是我通过 Postman 调用 API 的方式。

{
 "customerIds" : [69,50]
}

Content-Type = application/json

但是,如果我按如下方式更新 API,则会捕获值。

public HttpResponseMessage Delete(CustomerTO customerIds)
{
    //api stuff
}
public class CustomerTO
{
   public IEnumerable<int> CustomerIds
}

如果我这样做,我认为这是一个开销。

非常感谢任何帮助/建议。

【问题讨论】:

  • 您传入的对象具有名为customerIds 的属性。你需要传入一个整数数组,[59,60]
  • public IEnumerable&lt;int&gt; CustomerIds替换CustomerTO customerIds
  • 或在您的 json 中将 "customerIds" : [69,50] 替换为 "customerIds" : {"cutomerIds": [69,50]}
  • @Alex:用IEnumerable&lt;int&gt; CustomerIds 替换CustomerTO customerIds 只会给你原件,不是吗?或者您是否正在考虑替换其他地方(不确定在哪里可以使用 public 关键字,所以试图猜测您的意思)。另外,我什至不确定您对第二条评论的想法。这将如何帮助更简单的代码工作?这不会让事情变得更糟吗?
  • @Chris,我的错。没有仔细阅读问题。 @Kgn-web 是HTTPDELETE 的请求吗?

标签: c# json asp.net-web-api postman


【解决方案1】:

对于第一个,我认为您可能需要这样做:

([FromBody] IEnumerable<int> customerIds)

【讨论】:

  • [FromBody] 属性指定值将来自正文或 url 的位置。就是这样
  • 使用这种方法,您还需要通过邮递员而不是对象发送数组。
【解决方案2】:

问题出在您的帖子数据对象中。 您只需在请求数据中传递一个数组[1,2,3,4]

【讨论】:

  • 但这不是一个有效的 json [1,2,3,4]
  • 为什么它无效,我已经测试过它并且工作正常
  • 是的。我的错。我很抱歉。
猜你喜欢
  • 2017-03-11
  • 1970-01-01
  • 2012-03-27
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多