正确地形成通用的RESTful路由方案

时间:2012-03-02 14:51:33

标签: asp.net-mvc-3 rest routes asp.net-mvc-routing

我在ASP.NET MVC 3中有一些路由。我想要实现的是要正确处理以下URL:

/users
/users/123
/users/123/modules
/users/123/modules/1
/users/123/modules/1/modulesettings
/users/123/modules/1/modulesettings/642

我还希望能够支持所有标准的HTTP动词。现在,我尝试在我的Global.asax中创建一些路由,但似乎总有一条路由无法正常工作。以下是我到目前为止的情况:

routes.MapRoute("RESTSubEntity",
            "{entity}/{entityId}/{subEntity}/{subEntityId}/{controller}/{id}/{action}", // action is the associated entity plurality
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new { id = @"\d+", entityId = @"\d+", subEntityId = @"\d+" });

routes.MapRoute("RESTEntity",
            "{entity}/{entityId}/{controller}/{id}/{action}", // action is the associated entity plurality
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new { id = @"\d+", entityId = @"\d+" });

routes.MapRoute("REST",
            "{controller}/{id}/{action}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new { id = @"\d+" });

routes.MapRoute("Default",
            "{controller}/{action}/{id}",
            new { controller = "Home", action = "Index", id = UrlParameter.Optional });

丑陋,我知道。我想知道是否有办法让我的所有路线都尽可能地使用通用路线。谢谢!

1 个答案:

答案 0 :(得分:0)

事实证明,问题在于你无法将约束与可选参数结合起来,这非常有意义。这是我现在使用的路由方案:

routes.MapRoute("Resource",
    "{controller}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional });

routes.MapRoute("SubResource",
    "{entityType}/{entityId}/{controller}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new { entityId = @"\d+" });

routes.MapRoute("SubSubResource",
    "{entityType}/{entityId}/{subEntity}/{subEntityId}/{controller}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new { entityId = @"\d+", subEntityId = @"\d+" });

routes.MapRoute("Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional });