0

So I am trying to pass a string to my Web Api through a put call in an Angular service. The service actually calls the method on the Web Api side, but the parameter always comes through null. Can someone shed a bit of light, thanks.

Here is what the code looks like:

Web Api: (the breakpoint is set on the first parenthesis)

public void Put([FromBody]string userId)
{


} 

Angular :

 UpdateManagerEmail(userId){
    userId = '577f1e6e-146d-49f1-a354-b31349e7cb49';
    const headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');

    this._http.put('http://localhost:428/api/User', {
        userId : userId
    }).subscribe(returnVal => {
      console.log('returned');
    });
  }
6
  • Do you see the parameter being sent in your request within network tab of developer tools? Commented Aug 15, 2018 at 13:55
  • I can see it in the Request payload Commented Aug 15, 2018 at 13:58
  • Have you tried removing [FromBody] ? Commented Aug 15, 2018 at 14:00
  • without FromBody, it controller isn't called Commented Aug 15, 2018 at 14:06
  • have you tried wrapping the string in quotes? this._http.put('http://localhost:428/api/User', '"' + userId + '"') OR setting a variable var data = userId and just passing data into the put method? this._http.put('http://localhost:428/api/User', data) Commented Aug 15, 2018 at 14:11

1 Answer 1

1

For your backend to find userId in the request body you have send it needs to be the only value in there. You should change the content-type to: application/x-www-form-urlencoded; charset=UTF-8 and send the data without an key.

Remark on the docs:

Before sending a simple type, consider wrapping the value in a complex type instead. This gives you the benefits of model validation on the server side, and makes it easier to extend your model if needed.

Source: Sending simple types

Also, this blog explains it better than I do.

Sign up to request clarification or add additional context in comments.

Comments

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.