I am using mvc webapi to create a REST API and struggling to find an example dealing with POSTs to nested resources.
我正在使用mvc webapi创建REST API,并努力寻找一个处理嵌套资源的POST的示例。
Basically, I want to POST
a comment to a blog post using a URL like:
基本上,我想使用以下URL来发布评论到博文:
~/posts/2/comments
〜/职位/ 2 /评论
I would also like to be able to send DELETE and PUTs
to the following
我还希望能够将DELETE和PUT发送到以下内容
~/posts/2/comments/5
〜/职位/ 2 /评论/ 5
What should my route registration look like, and what should my method signature on my PostsController
look like?
我的路由注册应该是什么样的,我的PostsController上的方法签名应该是什么样的?
Thanks!
谢谢!
1 个解决方案
#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
框架中没有嵌套资源的约定,但路由使您可以灵活地映射控制器,方法和URI,但是您认为合适
#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
框架中没有嵌套资源的约定,但路由使您可以灵活地映射控制器,方法和URI,但是您认为合适