17

我们有一个 .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',
  })
}

一定是一件容易实现的事情吗?

4

3 回答 3

30

您的代码几乎所有东西都很好。主要问题是Content-Type标题。如果您想将字符串发送到带有注释的.NETREST API并使用标头值,您应该添加到路径参数中,例如:[FromBody]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',
  })
于 2018-04-25T11:59:13.287 回答
5

您可以通过删除属性来获取pathfromquery[fromBody]

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',
  })
于 2018-04-29T15:38:38.573 回答
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);
                });
            });
          }

如果它有效,我会很高兴。谢谢

于 2018-05-02T07:47:20.343 回答