从Typescript到Web API API的POST,无法传递JSON对象 [英] POST from Typescript to Web API API, unable to pass a JSON Object

查看:432
本文介绍了从Typescript到Web API API的POST,无法传递JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将JSON对象从打字稿POST调用传递到Web API方法. Fiddler显示该对象已转换为JSON,并且Content-Type为'application/JSON'.但是在API控制器上,参数值显示为空而不是JSON.

I am trying to pass a JSON Object from a typescript POST call to a Web API method. Fiddler shows that the object has been converted into JSON and the Content-Type is 'application/JSON'. But at the API controller, the parameter value displays null instead of JSON.

打字稿:

createPO(product: string): Promise<string> {
   var headers = new Headers();
   headers.append('Content-Type', 'application/json');
   let options = new RequestOptions({ headers: headers });
   return this._http.post(this._creatPOUrl, JSON.stringify(product), options)
   .toPromise()
   .then(response => <string>response.statusText)
   .catch(this.handleError);
   }

Web API: [HttpPost] 公共异步任务CreatePOInMO([FromBody]字符串产品) { 返回Ok(); }

Web API: [HttpPost] public async Task CreatePOInMO([FromBody] string product) { return Ok(); }

产品包含空值. 如果我将实际值传递给typescript(是JSON)的product对象,它将起作用.但是我不能像这样硬编码.

product contains null. If I pass the actual value inside product object from typescript(which is a JSON) , it works. But I cannot hard code like this.

我关注了这篇文章: Angular2服务未将JSON传递给WebAPI 但是看来我正在做这里提到的任何事情.

I followed this post : Angular2 Service not passing JSON to WebAPI But it looks like I am doing whatever is mentioned here.

推荐答案

在Angular 2中,当

In Angular 2, when posting JSON with the Http client, you should not call JSON.stringify:

this._http.post(this._creatPOUrl, product, options)

这篇关于从Typescript到Web API API的POST,无法传递JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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