使用asp webapi发布嵌套资源

Pau*_*aul 7 rest asp.net-mvc asp.net-web-api

我正在使用mvc webapi创建REST API,并努力寻找一个处理嵌套资源的POST的示例.

基本上,我想POST使用以下网址对博客文章发表评论:

~/posts/2/comments

我也希望能够发送DELETE和PUTs以下内容

~/posts/2/comments/5

我的路线注册应该是什么样的,我的方法签名应该是什么PostsController样的呢?

谢谢!

cec*_*lip 9

对于嵌套资源,我建议您为要访问的控制器/操作创建非常具体的路由.

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
}
Run Code Online (Sandbox Code Playgroud)

框架中没有嵌套资源的约定,但路由使您可以灵活地映射控制器,方法和URI,但是您认为合适