Using asp webapi to host a nested resource

I am using mvc webapi to create a REST API and am trying to find a POST related example for nested resources.

Basically, I want to POST comment on a blog post using a URL, for example:

~/posts/2/comments

I would also like to send DELETE and PUTs to the next

~/posts/2/comments/5

What should my route registration look like and what should my method signature look like on my PostsController ?

Thanks!

+7
source share
1 answer

For nested resources, I would suggest creating very specific routes for the controllers / actions that you want to access.

 routes.MapHttpRoute( name: "Posts Routes", routeTemplate: "api/posts/{postId}/comments/{commentID}", defaults: new { controller = "Posts", action="CommentsForPosts" } ); public HttpResponseMessage CommentsForPosts(int postId, int commentID) { //go to work } 

There is no agreement in the structure of nested resources, but routing gives you the flexibility to map your controllers, methods, and URIs, however you consider it necessary

+9
source

All Articles