【问题标题】:angular 4 web api post (data) method is not working 415 errorangular 4 web api post(数据)方法不起作用415错误
【发布时间】:2018-09-16 09:52:02
【问题描述】:

我是 angular 4 web api 的新手。我想使用 angular 4 web api 将一些数据保存到数据库中。当我从角度调用 GET 方法时,它工作正常,但不适用于 POST 方法。我收到 415 不支持的媒体类型。一直以来,但是当我使用 postman 时,post 方法工作正常,因为我将内容类型更改为 application/json。但是在角度上它不起作用......我看到很多相同问题的问题,但它们对我不起作用。在这里,我添加了一些硬编码数据。

这是我的组件 ts 文件:

   fulldetail: Idetails[] =[];
detail: Idetails;
  onClick(value:any) {


       \\hardcoded data
        this.id = 1;
       this.name= abcd;
        this.address= "abcdefgh";
        this.about= "samplestring";
        this.number= 18888;
        this.count = 12.0;

  this._Service.CatchDetail(this.id, this.name, this.address, 
this.about, this.number, this.count)
           .subscribe(detail=> {
                detail.forEach(value => {
                    this.fulldetails.push(value)
           });
        },
            error => {
                console.error(error);
                this.statusMessage = "Problem with the service.Please try again after sometime";

        });

这是我的服务 .ts 代码:

CatchDetail(id: number, name: string, address: string, 
about: string, number: number, count: number)
    : Observable<Idetails[]> {
      let data= JSON.stringify([{ id: id, name: name, address: address, about: about, nu: number, count: count }]);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });
    return this._http.post('http://localhost:1234/api/contrllername/' + 'detail', data,
        {
            params: [{ id: id, name: name, address: address, about: about, nu: number, count: count }]
        })
        .map((response: Response) => <Idetails[]>response.json())
        .catch(this.handleError)
}

这是 workdetails.ts(类):

export class Idetails {
constructor(
    public id: number,
    public name: string,
    public address: string,
    public about: string,
    public number: number,
    public count: number
  ) { }
}

这是我的控制器:

   [HttpPost]
    public void Detail([FromBody] List<spGetDetails_Result> jsonvalues)

    {


        foreach (spGetDetails_ResultDatadetail in jsonvalues)
        {
            spGetDetails_ResultDetailobject = new spGetDetails_Result();

            Detailobject.id = Datadetail.id;
            Detailobject.name= Datadetail.name;
            Detailobject.address= Datadetail.address;
            Detailobject.about= Datadetail.about;
            Detailobject.number= Datadetail.number;
            Detailobject.count = Datadetail.count;

            enqentities.spGetDetails_Result(Datadetail.id, Datadetail.name, Datadetail.address, Datadetail.about, Datadetail.number, Datadetail.count);
        }

    }


    public class spGetDetails
    {

        public int id { get; set; }
        public string name{ get; set; }
        public string address{ get; set; }
        public string about{ get; set; }
        public int number{ get; set; }
        public int count { get; set; }

    }
}

zone.js:2933 POST http://localhost:1234/api/controllername/Detail?id=1&name=abc&address=hj1hgj368&about=dfghjkl&number=31&count=3 415(不支持的媒体类型)。 身体 : "{"Message":"此资源不支持请求实体的媒体类型 'text/plain'。","ExceptionMessage":"没有 MediaTypeFormatter 可用于从包含媒体的内容中读取类型为 'List`1' 的对象输入“文本/纯文本”............等

【问题讨论】:

  • 这是一个 CORS 问题。Look at this answer
  • 你能发布你的控制器方法吗?
  • 控制器方法已经发布,这里我使用asp.net mvc web api
  • 我认为我在 component.ts 文件中的错误(不确定)
  • @shabad faiz 对。它看起来像 cors

标签: angular typescript asp.net-web-api angular2-routing angular4-forms


【解决方案1】:

我今天遇到了这个问题,并通过简单地将 Web API 项目托管在 IIS 而不是 IIS Express 中解决了这个问题。即使来自 Angular 的请求实际上是正确的,它也只是在返回 415 的 OPTIONS 请求中失败。

【讨论】:

    【解决方案2】:

    我看到了几个问题:

    1. 您的控制器返回void,而您的角度则期待响应.map(res =&gt; res.json());
    2. List&lt;spGetDetails_Result&gt; 在您的控制器中,但您有 spGetDetails 类。
    3. 我相信您正在从您的帖子请求中发送一个对象,但在您的控制器中,您期待 List&lt;T&gt;
    4. 您正在向http://localhost:1234/api/contrllername/' + 'detail 发送发布请求,您的控制器是否名为contrllername?除非您设置了正确的路由,否则/detail 会触发您的操作Stock
    5. 我也不认为你需要stringify,你可以简单地传递你的Idetails对象,它会映射到spGetDetails

    【讨论】:

    • 但是当使用 prostman 时,我可以成功收到详细信息。所以我可以告诉我的问题是 4 角
    • 实际上我想向我的控制器发送一些列表,所以我期待 List 另一个问题是如何映射到 spget 详细信息??
    • @j4rey89 不使用 http,使用 httpClient(所以,不使用 map(res=>res.json)。无论如何,我看到的主要问题是控制器需要一个“数组”,而 Anjana正在发送一个对象,必须发送 [{id:...,name:...}]
    • @Eliseo 我还检查了 [{id:...,name:...}] 是否像这样?同样的错误反映。
    • @anjanasnair,还有一个问题,您使用“参数”作为发送“数据”的方式。必须 let data=[{ id: id, name: name, address: address, about: about, nu: number, count: count }]; this._http.post('localhost:1234/api/contrllername' + '详细信息',数据})。 http 的参数“params”是更改标头或其他选项。无论如何,使用 httpClient(你会忘记 json、jsonStringify 等)
    【解决方案3】:

    如果你的服务是这样的,必须工作

    constructor(httpClient:HttpClient){}
    CatchDetail(id: number, name: string, address: string,
               about: string, number: number, count: number)
        : Observable<Idetails[]> {
          let data= [
               { 
                 id: id, 
                 name: name, 
                 address: address, 
                 about: about, 
                 nu: number, 
                 count: count
               }];
        return this.httpClient.post('http://localhost:1234/api/contrllername/detail'
            , data)
    }
    

    【讨论】:

    • @anjanasnair,httpClient 以 json 格式发送请求。我不明白,因为您收到了错误 415 not suported media :(
    • 能否请您在 Angular 4 Web api 发布方法中发送演示链接?
    【解决方案4】:

    我认为您只是忘记将标头添加到请求中。

    使用 httpClient 代替 Http(Angular 4.3+):

    import { HttpHeaders } from '@angular/common/http';
    
    const httpOptions = {
        headers: new HttpHeaders({
            'Content-Type':  'application/json'
          })
    };
    return this.httpClient
               .post(url, data, httpOptions ) <-----
               .subscribe((response: Response) => {
                   // do what you want with the response.
               });
               // you do not have to parse to JSON with httpClient!
    

    如果您无法使用 httpClient,请查看以下帖子:
    https://stackoverflow.com/a/46172188/243896

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 2017-09-07
      • 2018-02-16
      • 1970-01-01
      • 2021-04-27
      • 1970-01-01
      • 2018-03-24
      • 2018-11-07
      • 1970-01-01
      相关资源
      最近更新 更多