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

半世苍凉 提交于 2020-01-03 17:05:12

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/35542785/posting-object-from-angular-2-application-to-web-api-application-getting-unsupp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!