0
votes

I am new in angular 4 web api. I want to save some data to database using angular 4 web api. When i call a GET method from angular it works fine, but not working on POST method. I am getting 415 Unsupported Media Type. All the time, but when I use postman the post method is work fine because I change the content type to application/json. But in angular it's not working... I see lots of issues with the same problem, but they don't work for me. Here I add some hardcoded data.

This is my component ts file:

   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";

        });

And this is my service .ts code:

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

And this is workdetails.ts (class):

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

This is my controller:

   [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(Unsupported Media Type). body : "{"Message":"The request entity's media type 'text/plain' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'List`1' from content with media type 'text/plain'...........etc

4
This is a CORS issue.Look at this answerShadab Faiz
Can you post your controller method?Niladri
controller method has been posted,here i use asp.net mvc web apiuser9495407
i think my error in component.ts file(not sure)user9495407
@shabad faiz right. it looks about corsarslanaybars

4 Answers

0
votes

I think you just forgot to add your header to the request.

Use httpClient instead of 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!

If you cant use httpClient, lookup following post:
https://stackoverflow.com/a/46172188/243896

0
votes

Must work if your service is like

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)
}
0
votes

There are a couple of issues I see:

  1. Your controller returns void whereas your in your angular you are expecting a response .map(res => res.json());
  2. List<spGetDetails_Result> in your controller but you have spGetDetails class.
  3. I believe your are sending one object from you post request but in your controller you are expecting List<T>
  4. You are sending a post request to http://localhost:1234/api/contrllername/' + 'detail, Is your controller named contrllername? And unless you have set up a proper routing why will /detail hit your action Stock?
  5. I also don't think you need to stringify, you can simply pass your Idetails object, and it will be mapped to spGetDetails
0
votes

I banged my head against this today and solved it by simply hosting the Web API project in IIS rather than IIS Express. It was only failing in the OPTIONS request coming back with a 415 even though the request from Angular was in fact correct.