【问题标题】:Is the Web API routing engine smart enough so that identical routing attributes can be applied to different methods?Web API 路由引擎是否足够智能,可以将相同的路由属性应用于不同的方法?
【发布时间】:2014-02-12 18:23:33
【问题描述】:

考虑一个具有此路由属性的方法:

[Route("api/Deliveries/{ID:int}/{CountToFetch:int}")] 

具有这些路由属性的方法由客户端调用,传递如下 URI:

http://localhost:28642/api/deliveries/42/100

这样,路径信息(“api/Deliveries”)和参数({ID:int}/{CountToFetch:int})看起来是同质和/或同源的。

被调用的控制器上的方法获取分配给它的这些参数,因为这很清楚:

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 中传递的参数和/或基于两种方法的不同返回类型调用适当的方法(例如,前者返回 IEnumerable of Delivery,而后者返回单个交付)?

【问题讨论】:

  • 你试过了吗? :-) 我的猜测是它只使用 url 路径而不是查询字符串,但尝试起来更容易。
  • 不,问已经知道的人更容易。不过我会试试的。

标签: c# rest uri url-routing asp.net-web-api-routing


【解决方案1】:

是的,Web API 路由引擎即使不如 Einstein 聪明,也至少和普通的 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() 被调用。

【讨论】:

    猜你喜欢
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2018-11-17
    • 2012-07-12
    • 2015-08-11
    • 1970-01-01
    • 2014-08-18
    相关资源
    最近更新 更多