By namrata


2017-01-11 20:11:09 8 Comments

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 comments

@cartant 2017-01-11 20:14:55

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

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

@namrata 2017-01-11 20:26:49

Changed it to : var POCartItems = JSON.stringify(product); return this._http.post(this._creatPOUrl, POCartItems , options) and at Web API: [HttpPost]public async Task<IHttpActionResult> CreatePOInMO([FromBody] string POCartItems) Still not working.

@cartant 2017-01-11 20:29:22

I'm not sure what you mean. The JSON.stringify call is not required. Have a look at the linked documentation/guide.

Related Questions

Sponsored Content

43 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

26 Answered Questions

[SOLVED] Convert JS object to JSON string

29 Answered Questions

[SOLVED] How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

27 Answered Questions

[SOLVED] Safely turning a JSON string into an object

  • 2008-09-05 00:12:01
  • Matt Sheppard
  • 1277658 View
  • 1355 Score
  • 27 Answer
  • Tags:   javascript json

9 Answered Questions

2 Answered Questions

pass value as empty string to WEb API from typescript

7 Answered Questions

[SOLVED] Angular2 HTTP Post ASP.NET MVC Web API

1 Answered Questions

[SOLVED] Simple post to Web Api

1 Answered Questions

Sponsored Content