【问题标题】:Angular - calling web api HttpPost with FromBody string - body is always nullAngular - 使用 FromBody 字符串调用 web api HttpPost - 正文始终为空
【发布时间】:2019-01-07 17:08:41
【问题描述】:

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

我有一个 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 用于简单字符串的原因是它可能很长。
  • 我知道我可以用模型包裹字符串并且它会起作用,但我想知道我在这里是否缺少一些东西来这样做

我在这里做错了什么?

【问题讨论】:

  • 那么,您知道如何进行这项工作,但您不想这样做?

标签: angular asp.net-web-api2


【解决方案1】:

嗯,最后还是很简单的回答:

只需在字符串对象上使用 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

【讨论】:

    猜你喜欢
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 2018-12-26
    • 2015-08-11
    • 1970-01-01
    相关资源
    最近更新 更多