0

我有两个类之间的多对多关系:供应商和产品。

在我的 Web API 中,每个类都有一个控制器。两个控制器都具有明显的操作,即获取对象列表和通过 Id 获取单个对象。

我需要的是一个为每个对象获取许多对象的操作。例如,如果我提供了 VendorId,那么我想要 Vendor 提供的所有产品。同样,如果我提供 ProductId,那么我想要所有提供产品的供应商。

我有三个问题:

1) 我认为 Product 控制器应该具有接受 VendorId 并返回 Products 的操作(对于 Vendor 控制器反之亦然)。这是“正确”的方法吗?

2)我如何实现上述?我不能只添加另一个采用 Id 的 Get 操作,因为控制器已经具有具有该方法签名的操作(单项方法)。

例如:

http://localhost:53962/api/product/1         // grabs product with Id = 1.
http://localhost:53962/api/product/vendor/1  // causes 404

3) 当我想要特定供应商的所有产品时,Url 应该是什么样子?

4

1 回答 1

1

1) I think the Product controller should have the action that takes a VendorId and returns the Products (and visa-versa for the Vendor controller). Is this the "proper" approach?

Yes, this will work. For example, you can have 2 such actions in your ProductController:

    public Product Get(int id) {...}
    public Product GetProductWithVendorId(int vendorId) {...}

2) How do I implement the above? I can't just add another Get action that takes an Id because the controllers already have an action with that method signature (the single item method).

That is correct if you want to call the above 2 actions using route parameter. There are different ways to approach this. One way is to modify your route. Another way is to pass the action parameter in the URL.

3) What should the Url look like when I want all the Products for a specific vendor?

Here is an example of passing parameter in the URL. This URL will invoke the ProductController's 'Get' action:

http://../api/product/123

This URL will invoke the ProductController's 'GetProductWithVendorId' action:

http://../api/product?vendorid=456
于 2012-11-06T19:33:40.993 回答