0

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 Answers4

0

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
j4rey
  • 2,582
  • 20
  • 34
  • But when using prostman, I could succesfully receive the details.so i can tell my problm is in angular 4 –  Apr 10 '18 at 10:20
  • actually i want to send some list to my controller, so i expecting List and another quetion is how to be mapped to spget details?? –  Apr 12 '18 at 07:00
  • @j4rey89 NOT use http, use httpClient (so, not use map(res=>res.json). AnyWay, the main problem I see is that the controller expect an "array", and Anjana is sending an object, must be send [{id:...,name:...}] – Eliseo Apr 17 '18 at 06:39
  • @Eliseo i also check that [{id:...,name:...}]like this ?same error reflect. –  Apr 27 '18 at 10:29
  • @anjanasnair, there're one problem more, you're using "params" as the way to send the "data". Must be let data=[{ id: id, name: name, address: address, about: about, nu: number, count: count }]; this._http.post('http://localhost:1234/api/contrllername/' + 'detail',data}). The arguments "params" of the http is to change the headers or another options. Anyway, use **httpClient** (you'll forget the json, jsonStringify and so) – Eliseo Apr 27 '18 at 12:44
  • @Eliseo thanks for your reply, anyway i changed as you said but i still got the same error? –  Apr 30 '18 at 05:37
  • @anjanasnair, have you try dimiSchenk answer? – Eliseo Apr 30 '18 at 07:07
  • @Eliseo thanks man for your comment ,i m still in this error. –  May 02 '18 at 11:55
  • @Eliseo can you please sent a demo link in angular 4 web api post method? –  May 03 '18 at 06:25
  • @Eliseo Does error is in component .ts file? its only a doubt? –  May 03 '18 at 06:27
0

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

domiSchenk
  • 880
  • 4
  • 23
  • 41
0

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)
}
Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • @anjanasnair, httpClient send a request in json format. I dont understand as you received a error 415 not suported media :( – Eliseo May 02 '18 at 21:47
  • can you please sent a demo link in angular 4 web api post method? –  May 03 '18 at 06:24
0

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.

Sean Chase
  • 1,139
  • 1
  • 15
  • 23