Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 views
in Technique[技术] by (71.8m points)

rest - Nested resources in ASP.net MVC 4 WebApi

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).

For example I want to handle:

/customers/1/products/10/

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

Add this under default route:

routes.MapHttpRoute(
    name: "OneLevelNested",
    routeTemplate: "api/{controller}/{customerId}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

This route will then match any controller action and the matching segment name in the URL. For example:

/api/customers/1/orders will match:

public IEnumerable<Order> Orders(int customerId)

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

public Order Orders(int customerId, int id)

/api/customers/1/products will match:

public IEnumerable<Product> Products(int customerId)

/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.


Important Note:

From comments

Since the RC you'll need to tell each action which kind of verbs that are acceptable, ie [HttpGet], etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...