如何在ASP.NET MVC中映射Post/[id]/Comments/[Action]?

the*_*row 2 asp.net-mvc asp.net-mvc-routing

我想为我的博客应用程序创建一个RESTful API,但我不知道如何映射这样的控制器.
怎么做到呢?Post应该在URL模式中进行硬编码吗?

Ufu*_*arı 5

你可以映射这样的路线:

routes.MapRoute(
        "ShowComments", // Route name
        "Post/{id}/Comments/{action}", // URL with parameters
        new { controller = "CommentsController", action = "Show" } // Parameter defaults
        );
Run Code Online (Sandbox Code Playgroud)

硬编码URL没有任何问题,除非您添加的所有内容都需要硬编码的URL并且它们变得不可维护.

我的理解是你想要只通过这条路线调用的CommentsController.您不希望默认路由调用它.你可以用IgnoreRoute它.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute(“Comments/{action}/{id}”);
}
Run Code Online (Sandbox Code Playgroud)

这将确保没有我们之前定义的路由就不会调用CommentsController.我希望那就是你想要做的.