0

I am passing this URI to my Web API server:

http://localhost:28642/api/InventoryItems/PostInventoryItem?serialNum=8675309e9&ID=147&pksize=2&Description=juanValdes&vendor_id=venderado&UnitCost=2.58&UnitList=3.82&OpenQty=25.70&UPC=12349&dept=139&subdept=89&upc_pack_size=24&vendor_item=popTartz&crv_id=157

This Controller code (with the "[FromBody]" annotation) does not work:

public void PostInventoryItem([FromBody] string serialNum, [FromUri] InventoryItem ii)
{
    string serNum = serialNum;
    _inventoryItemRepository.PostInventoryItem(serNum,
        ii.ID, ii.pksize, ii.Description, ii.vendor_id, ii.UnitCost, ii.UnitList, ii.OpenQty,
        ii.UPC, ii.dept, ii.subdept, ii.upc_pack_size, ii.vendor_item, ii.crv_id);
}

...(serialNum is null); but this (without the "[FromBody]" annotation) does:

public void PostInventoryItem(string serialNum, [FromUri] InventoryItem ii)
{
    string serNum = serialNum;
    _inventoryItemRepository.PostInventoryItem(serNum,
        ii.ID, ii.pksize, ii.Description, ii.vendor_id, ii.UnitCost, ii.UnitList, ii.OpenQty,
        ii.UPC, ii.dept, ii.subdept, ii.upc_pack_size, ii.vendor_item, ii.crv_id);
}

(serialNum is the expected "8675309e9") Why? One would think the more specific version would work but, although it compiles, serialNum is null with that first snippet.

I know you can't use two "[FromBody]" annotations in one method, as noted here, but is it the case that all other annotations are disallowed?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

1 Answers1

1

In your first implementation

public void PostInventoryItem([FromBody] string serialNum, [FromUri] InventoryItem ii)

{}

the value of serialNum is null as expected, because [FromBody] was trying to look for serialNum in the body of your message.

This is the definition of the attribute from MSDN:

FromBodyAttribute Class

An attribute that specifies that an action parameter comes only from the entity body of the incoming HttpRequestMessage.

Toan Nguyen
  • 11,263
  • 5
  • 43
  • 59
  • Okay, I was confused/wasn't thinking about the body/uri separation. I don't know what the "body" is, I guess - how can I pass something (which I guess is considered the "body") separate from what is being passed in the URI? So now I wonder if it's possible to use two [FromUri] annotations; however, it is working as-is (no annotation on serialNum, and a [FromUri] for the class/object, so it's no big deal, I'm just mainly curious. – B. Clay Shannon-B. Crow Raven Feb 12 '14 at 16:26
  • 1
    "body" here means the body of your request. By default the binder will look at your query string, so you don't need to decorate with FromUri, unless you want to bind data from different location like in the first scenario – Toan Nguyen Feb 12 '14 at 20:58