将角度2应用程序中的对象发布到Web Api应用程序(获取不支持的媒体类型)

Mik*_*kel 4 api http observable angular

我可以使用一些指南,将我的angular 2应用程序中的对象发送到Web API.

我知道如何从Web Api到我的angular 2应用程序获取对象,但似乎无法弄清楚post方法是如何工作的,或者即使我应该使用http.post方法.

我的angular 2应用程序有以下方法:

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

}
Run Code Online (Sandbox Code Playgroud)

"updatedReservation"是一个对象,我将其转换为JSON.

可以通过以下地址访问Web api:

HTTL://本地主机:52262/API/postbookings

Web Api控制器:

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

}
Run Code Online (Sandbox Code Playgroud)

我要做的是发送对象,根据对象具有的更改值更新我的数据库.如果这是确认,则发送回真或假,以便我可以重定向到确认页面.

有没有人知道不支持的媒体类型错误?,那与我发送的对象不是api方法所期望的有关吗?

希望有人能提供帮助.

Thi*_*ier 9

您需要Content-Type在发送请求时设置标头:

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);
     });
}
Run Code Online (Sandbox Code Playgroud)

别忘了导入这个类:

import {Http,Headers} from 'angular2/http';
Run Code Online (Sandbox Code Playgroud)