如何使用Angular 4.3 HttpClient在POST请求的主体中发布字符串?

19
我们有一个 .net WebAPI,在 post 请求的正文中查找文件路径字符串并返回相应的图像。我正在努力使用新的 httpClient 从 Angular 4.3 成功地将字符串传递给它。这是可能的吗?该端点被其他东西使用,所以我不想创建一个字符串的“模型”,只是为了基本上复制它,但如果可能,传递它的 json。
WebAPI 方法签名:
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',
  })
}

变得简单易做的事情吗?

3个回答

31

你的代码几乎没有什么问题。主要问题在于 Content-Type 标头。如果您想向带有 [FromBody] 注释的 .NET REST API 发送字符串,并使用 application/json 标头值,您应该为路径参数添加 "",例如 "test_value"

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

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

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

添加引号很麻烦,而且在使用Swagger生成的代码时甚至不可能。我创建了一个HTTP拦截器,当您仅传递字符串并使用content-type application/json时自动添加引号。另请参见https://stackoverflow.com/questions/57323899/why-serializebody-method-in-request-ts-does-not-convert-json-stringifythis-body/66209414#66209414。 - Ramon de Klein

5

您可以通过删除[fromBody]属性,从query中获取path

public HttpResponseMessage ImagesFromPaths(HttpRequestMessage request, string path)

在发送 post 请求时,在路径中添加 ${apiUrl}/${path}

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

0

我刚刚尝试了另一种替代方法,通过这些选项并将字符串路径Json直接发布到post方法的正文中。

 getImage(path: string) {
            let headers = new Headers({ 'Content-Type': 'application/json' });
            let options = new RequestOptions({ headers: headers });

            return new Promise((resolve, reject) => {
                this.http.post('${apiUrl}',path, options)
                .map((res) => res.json()).share()
                .subscribe(res => {
                  resolve(res)
                }, (err) => {
                  reject(err);
                });
            });
          }

如果它能够正常工作,我会很高兴。谢谢。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接