考虑使用此路由属性的方法:
[Route("api/Deliveries/{ID:int}/{CountToFetch:int}")]
具有这些路由属性的方法由客户端调用,如下所示:
http://localhost:28642/api/deliveries/42/100
所以这样,路径信息(“api / Deliveries”)和args({ID:int} / {CountToFetch:int})似乎是同质和/或同源的。< / p>
调用的Controller上的方法会将这些args分配给它,因为这表明:
public IEnumerable<Delivery> GetBatchOfDeliveriesByStartingID(int ID, int CountToFetch)
{
return _deliveryRepository.GetRange(ID, CountToFetch);
}
这很好用。
但是还有另一种,也许更“接受”的形成路由属性的方法,其中args被排除在外:
[Route("api/Deliveries")]
...现在以这种方式调用GetBatchOfDeliveriesByStartingID():
http://localhost:28642/api/deliveries?ID=42&CountToFetch=100
这很好(也许);什么让我停下来是,现在的路由属性已经被简化,这样,如何路由引擎知道GetBatchOfDeliveriesByStartingID(),和GetDeliveryById()之间的差异,例如,目前有此路由属性:
[Route("api/Deliveries/{ID:int}")]
......但在新制度下会有:
[Route("api/Deliveries")]
......并且这样称呼:
http://localhost:28642/api/deliveries?ID=42
IOW,这两个方法具有完全相同的路由属性。
Web API路由机制是否足够智能,仍然可以根据URI中传递的args和/或基于两种方法的返回类型不同来调用适当的方法(例如,前者返回IEnumerable of Delivery,而后者返回一个交付)?
答案 0 :(得分:0)
是的,Web API路由引擎,如果不像爱因斯坦那样聪明,至少和平均值一样聪明Congressman
此代码:
[Route("api/Deliveries")]
public Delivery GetDeliveryById(int ID)
{
return _deliveryRepository.GetById(ID);
}
[Route("api/Deliveries")]
public IEnumerable<Delivery> GetBatchOfDeliveriesByStartingID(int ID, int CountToFetch)
{
return _deliveryRepository.GetRange(ID, CountToFetch);
}
......工作正常。
如果我通过了这个:
http://localhost:28642/api/deliveries?ID=7
... 调用GetDeliveryById()。
......如果我通过了这个:
http://localhost:28642/api/deliveries?ID=7&CountToFetch=42
调用... GetBatchOfDeliveriesByStartingID()。