[FromBody]和[FromUri]互相排斥吗?

时间:2014-02-11 23:58:39

标签: asp.net-mvc asp.net-web-api controller annotations frombodyattribute

我将此URI传递给我的Web API服务器:

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

此Controller代码(带有“[FromBody]”注释)不起作用:

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为null);但是这个(没有“[FromBody]”注释)确实:

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是预期的“8675309e9”)为什么?有人会认为更具体的版本可以工作,但是,虽然它编译,但是第一个片段的serialNum为null。

我知道你不能在一种方法中使用两个“[FromBody]”注释,如here所述,但是所有其他注释是否被禁止?

1 个答案:

答案 0 :(得分:1)

在您的第一次实施中

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

{}

serialNum的值按预期为空,因为[ FromBody ]试图在邮件正文中查找serialNum。

这是MSDN的属性定义:

FromBodyAttribute Class

  

指定动作参数仅来自的属性   传入的HttpRequestMessage的实体主体。