Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

posting object from angular 2 application to Web Api application (getting Unsupported Media Type)

I could use some guidens, sending an object from my angular 2 application to the Web API.

I know how to GET objects from the Web Api, to my angular 2 application, but can't seem to figure out how the post method works or even if I should use the http.post methodd.

My angular 2 application has the following method:

sendUpdatdReservation(updatedReservation: Reservation) {

    var result;
    var objectToSend = JSON.stringify(updatedReservation);

    this.http.post('http://localhost:52262/api/postbookings', objectToSend)
    .map((res: Response) => res.json()).subscribe(res => result = res);

    console.log(result);

}

The "updatedReservation" is an object, which I convert to JSON.

The Web api can be reached by the following address:

httl://localhost:52262/api/postbookings

Web Api controller:

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class PostBookingsController : ApiController
{
    [AcceptVerbs()]
    public bool ConfirmBooking(Booking booking)
    {
        return true;
    }

}

What I'm trying to do is to send the object, update my database based on the changes values that the object has. Then send back true or false if this is a confirmation or not so I can redirect to confirmation page.

Do any know the unsupported media type error?, is that related to that the object i send is not what the api method expects?

Hope someone can help.

like image 825
Mikkel Avatar asked Jan 06 '23 14:01

Mikkel


1 Answers

You need to set the Content-Type header when sending the request:

sendUpdatdReservation(updatedReservation: Reservation) {
  var result;
  var objectToSend = JSON.stringify(updatedReservation);

  var headers = new Headers();
  headers.append('Content-Type', 'application/json');

  this.http.post('http://localhost:52262/api/postbookings', objectToSend, { headers: headers })
     .map((res: Response) => res.json()).subscribe(res => {
       this.result = res;
       console.log(this.result);
     });
}

Don't forget to import this class:

import {Http,Headers} from 'angular2/http';
like image 194
Thierry Templier Avatar answered Jan 16 '23 12:01

Thierry Templier