首页 > 解决方案 > 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 的单个参数?

谢谢!

标签: angularasp.net-coreangular-servicesangular8media-type

解决方案


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)
    );
}

推荐阅读