【问题标题】:How to post a string in the body of a post request with Angular 4.3 HttpClient?如何使用 Angular 4.3 HttpClient 在发布请求的正文中发布字符串?
【发布时间】:2017-11-17 16:08:30
【问题描述】:

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

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

【问题讨论】:

    标签: angular angular4-httpclient


    【解决方案1】:

    您的代码几乎所有方面都很好。主要问题是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 拦截器,当您只传递一个字符串并使用内容类型 application/json 时,它会自动添加引号。另见stackoverflow.com/questions/57323899/…
    【解决方案2】:

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

    public HttpResponseMessage ImagesFromPaths(HttpRequestMessage request, string path)
    

    并在post请求${apiUrl}/${path}中的post发送路径:

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

    【讨论】:

      【解决方案3】:

      我刚刚通过此选项尝试了另一种替代方式,并将字符串路径 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);
                      });
                  });
                }
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-04
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多