3

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
  • Can you post your WEB-API configuration ? I suppose the JSON converter does not expect the JSON format in the same way as the standard JSON for example I had a similar problem posting { name: 'test' } from front end ant the expected class in the be was { Name: 'test' } because of the camel case the WEB-API standard converter could not translate the response. also a request could be helpful Commented Jan 12, 2017 at 19:54

1 Answer 1

4

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

this._http.post(this._creatPOUrl, product, options)
Sign up to request clarification or add additional context in comments.

2 Comments

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.
I'm not sure what you mean. The JSON.stringify call is not required. Have a look at the linked documentation/guide.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.