7

I am using mvc webapi to create a REST API and struggling to find an example dealing with POSTs to nested resources.

Basically, I want to POST a comment to a blog post using a URL like:

~/posts/2/comments

I would also like to be able to send DELETE and PUTs to the following

~/posts/2/comments/5

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

Thanks!

1 Answer 1

9

For nested resources I would suggest that you create 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's no convention in the framework for nested resources but routing gives you the flexibility to map your controllers, methods, and URIs however you see fit

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.