【问题标题】:Properly form a generic, RESTful routing scheme正确形成一个通用的 RESTful 路由方案
【发布时间】:2012-03-02 14:51:33
【问题描述】:

我在 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 });

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

【问题讨论】:

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


    【解决方案1】:

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

    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 });
    

    【讨论】:

      猜你喜欢
      • 2010-11-24
      • 2014-01-23
      • 1970-01-01
      • 2016-03-11
      • 2014-03-11
      • 1970-01-01
      • 2017-07-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多