POST from Typescript to Web API API, unable to pass a JSON Object

徘徊边缘 提交于 2019-12-11 03:53:27

问题


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.

Typescript:

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] public async Task CreatePOInMO([FromBody] string product) { return Ok(); }

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.

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


回答1:


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

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


来源:https://stackoverflow.com/questions/41599878/post-from-typescript-to-web-api-api-unable-to-pass-a-json-object

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