angular - 415 不支持的媒体类型;Angular 到 ASP.Net Core API
问题描述
我有ASP.Net Core 2.1 API
。它看起来如下。
[HttpPost]
public async Task<IActionResult> Post([FromBody]string email) {
}
从邮递员调用时,我必须调用上面的 API,如下所示,标题设置为Content-Type = application/json
从应用程序调用相同的 API 时 Angular 8
。
public send(email: string) {
//other tried option #1 let obj = JSON.stringify(email);
//other tried option #2 let obj = this.http.post(API.Url, {email});
/other tried option #3 let obj =
return this.http.post(API.Url, email).pipe(
retry(2)
);
}
这是抛出以下错误: -
415 不支持的媒体类型;
如果调用更新了标题:-
/* httpOptions = new HttpHeaders({
'Content-Type': 'application/json'
}*/
public send(email: string) {
return this.http.post(API.User, email , httpOptions).pipe(
retry(2)
);}
它将错误抛出为
{"":["解析值时遇到意外字符:c.Path '', line 1, position 1."]}
如何调用上述 API,它接受来自 Angular 的名为 email 的单个参数?
谢谢!
解决方案
You need to serialize a string to make it a valid json
like this:
// some example method.
public send(email: string) {
const headers = new HttpHeaders({
'Content-Type': 'application/json'
});
const json = JSON.stringify(email);
return this.http.post(API.User, json, {headers: headers}).pipe(
retry(2)
);
}
推荐阅读
- opengl - 如何在 OpenGL 片段着色器中创建闪烁效果?
- server - Raspberry PI 如何在文件夹上挂载 webserver 目录
- reactjs - 使用 Hooks 在 React 中处理错误和显示消息的正确方法
- php - Laravel Slack 通知的奇怪行为
- r - 如何为分组数据图添加平均线
- android - 看这个“startActivityForResult()”代码,这个函数被弃用了。如何在片段中更改此代码?
- ios - 使用 numberOfTouchesRequired 实现与 TrackPad 的二次点击
- android - java.lang.Object android.content.Context.getSystemService(java.lang.String) 错误
- firebase - 如何获取 Firebase 动态链接 URL 社交元数据本身
- python - 不同屏幕上的窗口变化