如何使用Angular 4.3 HttpClient在发布请求的正文中发布字符串? [英] How to post a string in the body of a post request with Angular 4.3 HttpClient?

查看:70
本文介绍了如何使用Angular 4.3 HttpClient在发布请求的正文中发布字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个.net WebAPI,它可以在发布请求的正文中查找文件路径字符串,并返回相应的图像。我正在努力使用新的httpClient成功从Angular 4.3中将字符串传递给它。可能吗?端点正在被其他东西使用,所以我真的不想创建一个字符串的模型,只是我基本上可以复制它,但是如果可能的话将其传递给json。

We've got a .net WebAPI which looks for a filepath string in the body of a post request and returns the corresponding image. I'm struggling to successfully pass a string to it from Angular 4.3 using the new httpClient. Is it possible? The endpoint's being used by other stuff so I don't really want to create a 'model' of... a string just so I can basically duplicate it but pass it json if possible.

WebAPI方法签名:

WebAPI method signature:

public HttpResponseMessage ImagesFromPaths(HttpRequestMessage request, [FromBody] string path)

当前服务方法:

getImage(path: string): Observable<any> {

  return this.http.post(
    `${apiUrl}`,
    { path },
    { headers: new HttpHeaders({
      'Content-Type': 'application/json',
    }), responseType: 'blob',
  })
}

要容易实现吗?

推荐答案

有您的代码几乎一切都很好。主要问题是 Content-Type 标头。如果要使用 [FromBody] 注释将字符串发送到 .NET REST API,请使用 application / json 标头值,应在路径参数中添加 ,例如 test_value

There is almost everything good with your code. Main issue is Content-Type header. If you want to send string to .NET REST API with [FromBody] annotation and use application/json header value you should add "" to your path param for example "test_value":

return this.http.post(
  `${apiUrl}`,
    `\"${path}\"` ,
  { headers: new HttpHeaders({
    'Content-Type': 'application/json',
  }), responseType: 'blob',
  })

您也可以使用 x-www -form-urlencoded 标头值。然后,您必须以这种方式将参数传递给请求正文:

You can also use x-www-form-urlencoded header value. Then you must pass your param to request body in that way:

return this.http.post(
  `${apiUrl}`,
    `=${path}` ,
  { headers: new HttpHeaders({
    'Content-Type': 'application/x-www-form-urlencoded',
  }), responseType: 'blob',
  })

这篇关于如何使用Angular 4.3 HttpClient在发布请求的正文中发布字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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