PUT request values always null
PUT request values always null
I'm trying to update an object to an API using PUT method, but when the update() method in the API is called, passed values are always null
.
null
Controller in the API :
[HttpPut]
[Route("{id:int}", Name = "UpdatePolicy")]
[SwaggerResponse(HttpStatusCode.NoContent, Description = "No Content")]
[ValidateModel]
public virtual void Update(int id, [FromBody]Policy p)
{
_policyBusinessService.Update(id, p);
}
Code from Angular component :
update(id) {
id = this.policyId;
this.policyModel.id = id;
console.log(this.policyModel);
this.policyService.update(this.policyId, this.policyModel).subscribe(res => {
// this.router.navigate(['/policies', id, 'get']);
}, (e) => {
console.log(e);
}
);
}
code from service :
update(id: number, pm: PolicyModel): Observable<PolicyModel> {
console.log(pm);
return this.http.put<PolicyModel>(`${environment.baseApiUrl}/${environment.apiVersion}/policies/${id}`, {pm});
}
what is passed to the PUT request :
{id: 1, name: "new name"}
So, the data sent from service is like just above. And in the api update()
method, the "Policy" object is always null
. I first thought it had to do with [FromBody]
but now I think it may have something to do with the JSON data format, but not sure..
update()
null
[FromBody]
And if that's right, what can I do to pass the right data in my request?
Thanks guys!
EDIT : It seems I was just missing the 'content-type' in the header. So I modified the service like this :
update(id: number, pm: PolicyModel): Observable<PolicyModel> {
console.log('before stringify :' + pm);
const stringifiedPm = JSON.stringify(pm);
console.log('after stringify :' + test);
return this.http.put<PolicyModel>(`${environment.baseApiUrl}/${environment.apiVersion}/policies/${id}`, stringifiedPm,
{headers: { 'Content-Type': 'application/json' }});
}
So now it works fine.
I was getting the error from angular. thing is i wasn't parsing the data properly. just edited my post with the fix. it seems to be okay now. update works fine :) Thanks for your time!
– j0w
Jul 2 at 13:47
Yep, I had the same problem a couple of months ago. You have to explicitly declare that you are sending JSON data in the message body.
– David R Tribble
Jul 2 at 15:07
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Where are you getting that error from ? From Angular or from your API ?
– Ulrich Dohou
Jul 2 at 12:56