4的WebAPI嵌套资源

4的WebAPI嵌套资源

本文介绍了在ASP.net MVC 4的WebAPI嵌套资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有新的ASP.net MVC 4的WebAPI处理嵌套的资源比建立一种特殊的路由为每一个更好的办法? (类似于此: - 这是在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).

例如我想处理:

/客户/ 1 /产品/ 10 /

我能比的get()命名其他 ApiController 动作的一些例子邮政()等,例如here我看到一个名为动作的一个例子 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 /客户/ 1 /订单将匹配:

/api/customers/1/orders will match:

public IEnumerable<Order> Orders(int customerId)

/ API /客户/ 1 /命令/ 123将匹配:

/api/customers/1/orders/123 will match:

public Order Orders(int customerId, int id)

/ API /客户/ 1 /产品将匹配:

/api/customers/1/products will match:

public IEnumerable<Product> Products(int customerId)

/ API /客户/ 1 /产品/ 123将匹配:

/api/customers/1/products/123 will match:

public Product Products(int customerId, int id)

方法名称必须与路由指定的{}行动段相匹配。

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嵌套资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 01:42