gpt4 book ai didi

asp.net-mvc-3 - 适本地形成一个通用的、RESTful 的路由方案

转载 作者:行者123 更新时间:2023-12-04 06:09:56 25 4
gpt4 key购买 nike

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

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

最佳答案

事实证明,问题在于您不能将约束与可选参数结合使用,这很合理。这是我现在使用的路由方案:

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

关于asp.net-mvc-3 - 适本地形成一个通用的、RESTful 的路由方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9535253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com