如何使用Angular 4.3 HttpClient在post请求主体中发布字符串?
我们有一个.NETWebAPI,它在post请求的主体中查找文件路径字符串并返回相应的图像。我正在努力使用新的httpClient成功地从Angular 4.3向它传递字符串。可能吗?端点正在被其他东西使用,所以我真的不想创建一个。。。一个字符串,这样我基本上可以复制它,但如果可能的话,可以将其传递给json WebAPI方法签名:如何使用Angular 4.3 HttpClient在post请求主体中发布字符串?,angular,angular4-httpclient,Angular,Angular4 Httpclient,我们有一个.NETWebAPI,它在post请求的主体中查找文件路径字符串并返回相应的图像。我正在努力使用新的httpClient成功地从Angular 4.3向它传递字符串。可能吗?端点正在被其他东西使用,所以我真的不想创建一个。。。一个字符串,这样我基本上可以复制它,但如果可能的话,可以将其传递给json WebAPI方法签名: public HttpResponseMessage ImagesFromPaths(HttpRequestMessage request, [FromBody]
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',
})
}
getImage(路径:字符串):可观察{
返回this.http.post(
`${APIRL}`,
{path},
{headers:新的HttpHeaders({
“内容类型”:“应用程序/json”,
}),响应类型:'blob',
})
}
这是一件很容易实现的事情吗?您的代码几乎具有所有优点。主要问题是
内容类型
标题。如果要将字符串发送到带有[FromBody]
注释的.NET
REST API,并使用应用程序/json
头值,则应将“
添加到路径参数中,例如测试值”
:
您还可以使用x-www-form-urlencoded
标题值。然后,您必须以这种方式将参数传递给请求主体:
return this.http.post(
`${apiUrl}`,
`=${path}` ,
{ headers: new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
}), responseType: 'blob',
})
通过删除
[fromBody]
属性,可以从查询中获取路径
public HttpResponseMessage ImagesFromPaths(HttpRequestMessage request, string path)
在post
request${apirl}/${path}
中的post发送路径中:
return this.http.post(
`${apiUrl}/${path}`,
{ headers: new HttpHeaders({
'Content-Type': 'application/json',
}), responseType: 'blob',
})
我只是通过这个选项尝试了另一种替代方法,并将post字符串路径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);
});
});
}
如果它能工作,我会很高兴的。谢谢添加引号很麻烦,而且在使用招摇过市生成的代码时甚至不可能。我创建了一个HTTP拦截器,当您只传递一个字符串并使用内容类型application/json
时,它会自动添加引号。另见
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);
});
});
}