问题描述
在新的 ASP.net MVC 4 WebApi 中,是否有比为每个资源设置特殊路由更好的方法来处理嵌套资源?(类似于此处:ASP.Net MVC 对嵌套资源的支持?- 这是 2009 年发布的).
Is there a better way in the new ASP.net MVC 4 WebApi to handle nested resources than setting up a special route for each one? (similar to here: ASP.Net MVC support for Nested Resources? - this was posted in 2009).
比如我要处理:
/customers/1/products/10/
我见过一些 ApiController
动作的例子,除了 Get()
、Post()
等,例如 我看到了一个名为 GetOrder()
的操作示例.不过,我找不到任何关于此的文档.这是实现这一目标的方法吗?
I have seen some examples of ApiController
actions named other than Get()
, Post()
etc, for example here I see an example of an action called GetOrder()
. I can't find any documentation on this though. Is this a way to achieve this?
推荐答案
抱歉,我已经更新了多次,因为我自己正在寻找解决方案.
Sorry, I have updated this one multiple times as I am myself finding a solution.
似乎有很多方法可以解决这个问题,但目前我发现最有效的方法是:
Seems there is many ways to tackle this one, but the most efficient I have found so far is:
在默认路由下添加:
routes.MapHttpRoute(
name: "OneLevelNested",
routeTemplate: "api/{controller}/{customerId}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
此路由随后将匹配 URL 中的任何控制器操作和匹配的段名称.例如:
This route will then match any controller action and the matching segment name in the URL. For example:
/api/customers/1/orders 将匹配:
/api/customers/1/orders will match:
public IEnumerable<Order> Orders(int customerId)
/api/customers/1/orders/123 将匹配:
/api/customers/1/orders/123 will match:
public Order Orders(int customerId, int id)
/api/customers/1/products 将匹配:
/api/customers/1/products will match:
public IEnumerable<Product> Products(int customerId)
/api/customers/1/products/123 将匹配:
/api/customers/1/products/123 will match:
public Product Products(int customerId, int id)
方法名称必须与路由中指定的 {action} 段匹配.
The method name must match the {action} segment specified in the route.
来自评论
因为RC你需要告诉每个动作哪种动词是可以接受的,即[HttpGet]
等
Since the RC you'll need to tell each action which kind of verbs that are acceptable, ie [HttpGet]
, etc.
这篇关于ASP.net MVC 4 WebApi 中的嵌套资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!