.NET Core 2 终结点在 POST 上不绑定 FromBody 的参数



我正在在我的Angular应用程序中进行以下调用。

this._client.post(
  "http://localhost:4300/api/Beep",
  { name: name, email: email })
  .subscribe(...);

我还尝试了明确的标头配置。

this._client.post(
  "http://localhost:4300/api/Beep",
  { name: name, email: email }),
  { headers: new HttpHeaders({ "Content-Type": "application/json" }) }
  .subscribe(...);

断点以以下方法捕获。

[HttpPost("Beep")]
public IActionResult RequestNetwork(
  [FromBody]string name, 
  [FromBody]string email)
{
  ...
  return Ok();
}

问题是两个字段均为null。

我不确定我是在前端侧还是后端侧的通话中在做愚蠢的事情。我验证了这样的代码与博客。我的赌注是在前者上,因为我遵循了Angular Docs,而且我还运行了Postman(将 content-type 设置为 application/json 并发送 {name:" QQQ",电子邮件:" www"} 作为RAW(。我尝试过的每个参数组合的结果相同。

在这个假设下,我一直在谷歌搜索类似于" 绑定核心帖子"的任何内容,包括我能想到的变体。我还没有发现任何我认识到的相关或有用的东西(可能是由于缺乏经验或挫败感引起的(

这里可能是什么问题,我应该寻找什么来解决它(或至少要深入到我遇到的任何错误(?

尝试使用类

public class DataType
{
   public string name { get; set; }
   public string email { get; set; }
}
//in your api
[HttpPost, ActionName("Beep")]
public IActionResult RequestNetwork([FromBody]DataType value)
{
  string name=value.name;
  string email=value.email;
  ...
  return Ok();
}

最新更新