Is the Web API routing engine smart enough so that identical routing attributes can be applied to different methods?

StackOverflow https://stackoverflow.com/questions/21736414

Question

Consider a method with this routing attribute:

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

The method with these routing attributes is called by the client passing a URI like this:

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

So this way, the path info ("api/Deliveries") and the args ({ID:int}/{CountToFetch:int}) appear to be homogeneous and/or homologous.

The method on the Controller that is called gets these args assigned to it, as this makes clear:

public IEnumerable<Delivery> GetBatchOfDeliveriesByStartingID(int ID, int CountToFetch)
{
        return _deliveryRepository.GetRange(ID, CountToFetch);
}

This works fine.

BUT there is another, perhaps more "accepted" way of forming routing attributes, where args are excluded:

[Route("api/Deliveries")] 

...wherewith GetBatchOfDeliveriesByStartingID() is now called this way:

http://localhost:28642/api/deliveries?ID=42&CountToFetch=100

This is fine (maybe); what gives me pause is, now that the routing attribute has been simplified so, how does the routing engine know the difference between GetBatchOfDeliveriesByStartingID(), and GetDeliveryById(), for instance, which currently has this routing attribute:

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

...but under the new regime would have:

[Route("api/Deliveries")] 

...and be called like so:

http://localhost:28642/api/deliveries?ID=42

IOW, the two methods have the exact same routing attribute applied to them.

Is the Web API routing mechanism smart enough to still invoke the appropriate method based on the args passed in the URI and/or based on the return type of the two methods being different (e.g., the former returns an IEnumerable of Delivery, whereas the latter returns a single Delivery)?

Était-ce utile?

La solution

Yes, the Web API routing engine is, if not as smart as Einstein, at least as smart as your average Congressman

This code:

[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);
}

...works fine.

If I pass this:

http://localhost:28642/api/deliveries?ID=7

...GetDeliveryById() is called.

...and if I pass this:

http://localhost:28642/api/deliveries?ID=7&CountToFetch=42

...GetBatchOfDeliveriesByStartingID() is called.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top