Everyone, we would like to introduce you to Anne Martinez. Aside from being a prolific writer, published author and successful businesswoman, Anne also happens to be a current student in our Day-Time Master Class!
Today we have the honor of sharing a snippet of one of her most recent weekly blogs, in which she details some of the things that she worked through and learned in Week 8 of Coder Foundry's 12 Week Coding Bootcamp.
HOW HARD CAN IT BE TO PASS AN INTEGER?
Anne Martinez - 02/24/15
Sending a variable to a Web API turned out much trickier than expected. If the stars align, it can go direct via Request URI or POST body, but if you want a sure thing, gift wrap it in an object.
The tricky part was passing variables to the Web API side in a manner it would cheerfully accept. Most of the class struggled with this. How hard can it be to pass an array of integers from one program (i.e. AngularJS) to another (i.e. the Web API)? Or even a single integer for that matter? For us newbies, it turned out to be a real challenge.
For starters, apparently where Web API looks for parameters depends on what type the parameter is, not necessarily whether you sent it via GET or POST. According to the ASP.NET Web site, if the expected parameter is a primitive type (for example int, bool, double), Web API will look for it in the request URI; if the parameter is something more complex, like an object, Web API will seek it out in the message body. The programmer has the power to encourage it to work otherwise by placing [FromURI] or [FromBody] annotations next to the parameter name in the controller, something like this:
public HttpResponseMessage MyMethod ([FromBody] int id)
This comes with gotchas, not the least of which is that you can only use [FromBody] on one parameter max per function. Throw into the mix the consideration that it’s generally encouraged to use the POST method if you’re sending variables to the server, which sends variables in the message body.
Continue reading by visiting Anne's original blog post, here.
While you're on her site, be sure to check out the rest of her blog as well, as she chronicles her way through Coder Foundry's bootcamp, detailing all of the new skills and technologies that she's picking up along the way!