Angular-使用FromBody字符串调用Web api HttpPost-正文始终为null [英] Angular - calling web api HttpPost with FromBody string - body is always null

查看:52
本文介绍了Angular-使用FromBody字符串调用Web api HttpPost-正文始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I really thought this is very simple, but I am not able to get this work.

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

I have a c# web api with the following mthod:

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

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

From the client, using angular httpClient, this is how I am trying to call the web api method:

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

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

When the call "arrives" to the server the id is fine, but the comment is always null.

注释:

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

我在做什么错了?

推荐答案

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

Well, in the end it is a very simple answer:

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

just use JSON.stringify on the string object

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

这篇关于Angular-使用FromBody字符串调用Web api HttpPost-正文始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆