[英]How to post a string in the body of a post request with Angular 4.3 HttpClient?
我們有一個 .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',
})
}
必須是一件容易實現的事情嗎?
您的代碼幾乎具有所有優點。 主要問題是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',
})
您可以通過刪除[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',
})
我只是通過這個選項嘗試了另一種替代方法,並將字符串路徑 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);
});
});
}
如果它有效,我會很高興。謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.