将对象从angular 2应用程序发布到Web Api应用程序(获取不受支持的媒体类型) [英] posting object from angular 2 application to Web Api application (getting Unsupported Media Type)

查看:48
本文介绍了将对象从angular 2应用程序发布到Web Api应用程序(获取不受支持的媒体类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

}

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

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

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

The Web api can be reached by the following address:

httl://localhost:52262/api/postbookings

httl://localhost:52262/api/postbookings

Web Api控制器:

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

}

我要执行的操作是发送对象,根据对象具有的更改值更新数据库.然后,如果这是一个确认,则返回true或false,因此我可以重定向到确认页面.

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.

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

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.

推荐答案

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

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

别忘了导入此类:

import {Http,Headers} from 'angular2/http';

这篇关于将对象从angular 2应用程序发布到Web Api应用程序(获取不受支持的媒体类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆