I've got a front end WebAPI written with angular and TypeScript that looks like this.
removeSubset(id: number): ng.IPromise<any> {
return this.$http.post(this.api + '/DeleteStudySubset', id)
.then(this.returnData);
}
returnData = (response: any) => {
return response.data;
};
And the back end version it calls out to is written like this
[HttpPost]
[ResponseType(typeof(IHttpActionResult))]
public async Task<IHttpActionResult> DeleteStudySubset(int id)
{
await _subsetRepo.DeleteStudySubset(id);
return Ok();
}
At first I was getting a URI 404 Error and I couldn't figure it out for the life of me. Then I stumbled across the parameter binding [FromBody] attribute and using it fixed the 404 issue.
So the back end API was rewritten to include the attribute and looked like so
[HttpPost]
[ResponseType(typeof(IHttpActionResult))]
public async Task<IHttpActionResult> DeleteStudySubset([FromBody] int id)
{
await _subsetRepo.DeleteStudySubset(id);
return Ok();
}
From what I think I vaguely understand [FromBody] is telling my back end to not reference the url that is pointing to the back end but search the body of what's being sent to it? Is that right? I don't think I'm explaining my hazy understanding well.
My more, to-the-point question is more or less outlined in the title and is: Is using the [FromBody] attribute on my back end to fix my 404 good practice, or is it more of a hack solution?
It feels like it was too easy of a solution and I'm worried if overall it is a non-elegant solution, and I just slapped a quick-fix on top of a more serious issue. Such as not configuring my front or back end API correctly to work in sync with one another.
Your type script is doing a post, and send the id in the body this is why you've got 404, you should change the typescript to do a get and leave the back-end as is, you do not need a body for the request so get should be just fine (send the id in the url of the get call). Or best practice it would be that the Delete actions to be actually DELETE http requests, to be more REST compliant, so you need to mark the back-end method with HttpDelete and change the type script to do a delete http request instead. I would recommend second option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With