【问题标题】:Web API Post Body Properties nullWeb API 帖子正文属性 null
【发布时间】:2018-08-10 23:06:30
【问题描述】:

我通过来自 Angular 应用程序的消息发布消息,并且每次帖子正文总是作为 null 进入函数。在发布请求确认该对象确实包含信息之前,直接在 Angular 应用程序中登录控制台,它似乎在整个过程中迷路了。

public class SentMessage
{
    public string MessageFrom { get; set; }
    public string MessageTo { get; set; }
    public string Message { get; set; }
}

// Post a new message
[Route("Conversation/AddTo")]
[HttpPost]
public IHttpActionResult AddToConversation(SentMessage message)
{
    if (message is null)
    {
        return NotFound();
    }

    return Ok("Message Sent");
}

到目前为止,我已经尝试过在其他帖子中建议的方法属性上使用和不使用 [FromBody],但过去我不确定出了什么问题。

........

【问题讨论】:

  • 如您所说,将[FromBody] 放在方法参数上,并确保您使用application/jsonContent-Type 发布。
  • 非常感谢 - 如果你想把它弹出来,如果你愿意,我会把它标记为你的答案?
  • 非常感谢。很高兴它对你有效。 :)

标签: c# asp.net-web-api2


【解决方案1】:

如您所说,将[FromBody] 放在方法参数上,并确保您使用Content-TypeContent-Type 发布。

【讨论】:

    【解决方案2】:

    只需修改代码

    public IHttpActionResult AddToConversation([FromBody]SentMessage message)
    {
        if (message is null)
        {
            return NotFound();
        }
    
        return Ok("Message Sent");
    }
    

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 1970-01-01
      • 2015-07-09
      • 1970-01-01
      • 2013-02-26
      • 2019-02-10
      • 1970-01-01
      • 2018-03-29
      • 2020-03-28
      相关资源
      最近更新 更多