415 不支持的媒体类型;Angular 到 ASP.Net Core API

Kgn*_*web 3 media-type angular-services asp.net-core angular angular8

我有ASP.Net Core 2.1 API。如下所示。

[HttpPost]
public async Task<IActionResult> Post([FromBody]string email) {

}
Run Code Online (Sandbox Code Playgroud)

当从邮递员调用时,我必须如下调用上述 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)
   );
}
Run Code Online (Sandbox Code Playgroud)

这引发了以下错误:-

415 不支持的媒体类型;

如果调用已更新标头:-

/* httpOptions = new HttpHeaders({
    'Content-Type': 'application/json'
}*/
public send(email: string) {
 return this.http.post(API.User, email , httpOptions).pipe(
  retry(2)
);}
Run Code Online (Sandbox Code Playgroud)

它抛出错误为

{"":["解析值时遇到意外字符:c.路径 '',第 1 行,位置 1。"]}

如何调用上面的 API,它接受来自 Angular 的名为 email 的单个参数?

谢谢!

Ale*_*der 5

您需要序列化一个字符串以使其有效,json如下所示:

// 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)
    );
}
Run Code Online (Sandbox Code Playgroud)