Angular-使用FromBody字符串调用Web api HttpPost-正文始终为null

时间:2019-01-07 17:08:41

标签: angular asp.net-web-api2

我真的认为这很简单,但是我无法完成这项工作。

我有一个带有以下方法的C#Web API:

[HttpPost]
public IHttpActionResult UpdateTaskComment(int id,[FromBody]string comment)
{
     //do something
}

从客户端使用有角的httpClient,这就是我试图调用Web api方法的方式:

let reqHeaders = new HttpHeaders().set('Content-Type','application/json');
this.http.post(`${BASE_URL}/UpdateTaskComment?id=${id}`,comment,{headers:reqHeaders})
         .subscribe(...)
         //catch error

当调用“到达”服务器时,id很好,但注释始终为空。

注释:

  • 我尝试对一个简单的字符串使用FromBody的原因是因为它可能很长。
  • 我知道我可以用模型将字符串包装起来,并且可以使用,但是我想知道是否缺少这种方法来实现这一目的

我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

嗯,最后,这是一个非常简单的答案:

只需在字符串对象上使用JSON.stringify

let reqHeaders = new HttpHeaders().set('Content-Type','application/json');
this.http.post(`${BASE_URL}/UpdateTaskComment?id=${id}`,JSON.stringify(comment),{headers:reqHeaders})
         .subscribe(...)
         //catch error