显然在 C# 中类不允许以数字开头,那么我如何在 ASP.NET 4.6 中为以数字开头的 URL 创建 Controller ?
示例网址:
www.domain.com/40apples/
编辑:单独路由每个 URL 很快就会变得难以管理。理想情况下,我正在寻找一种可以处理所有数字 URL 的解决方案。因此上面的 URL 示例路由到 _40apples Controller ,300cherries 到 _300cherries 和 1orange 到 _1orange
最佳答案
您将不得不使用自定义路由,在您的 RegisterRoutes 方法中您可以添加另一个看起来像这样的路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"ApplesRoute", // Route name
"40apples/{action}", // URL with parameters
new { controller = "Apples", action = "Index" } // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
如果您希望您的路由捕获任何以数字 + 苹果开头的内容,您可以使用正则表达式约束。像这样:
routes.MapRoute(
"ApplesRoute", // Route name
"{number}apples/{action}", // URL with parameters
new { controller = "Apples", action = "Index" } // Parameter defaults
,new {number = @"\d+" } //constraint
);
一种更通用的方法是捕获所有以数字 + 单词开头的路由。然后你可以像这样构建你的路线和约束:
routes.MapRoute(
"NumbersRoute", // Route name
"{numberfruit}/{action}", // URL with parameters
new { controller = "Numbers", action = "Index" } // Parameter defaults
,new { numberfruit = @"\d+[A-Za-z]" } //constraint
);
与 Organic 讨论后编辑:
解决这个问题的方法是使用属性路由。如果您使用的是 mvc 5 或更高版本,则效果很好。
然后您将向您的 Controller 添加一个类似于此的属性路由:
[RoutePrefix("40apples")]
然后是每个特定操作的另一条路线:
[Route("{Buy}")]
不要忘记将 routes.MapMvcAttributeRoutes();
添加到您的路由配置中。
关于c# - ASP.NET MVC 路由以数字开头的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37834463/