ASP.NET 以数字开头的 MVC 路由 URL

ASP.NET MVC routing URLs starting with numbers

显然在 C# 中 类 不允许以数字开头,所以我如何为 URL 创建以数字开头的控制器 ASP.NET 4.6?

示例URL:

www.domain.com/40apples/

编辑:单独路由每个 URL 将很快变得难以管理。理想情况下,我正在寻找一种可以处理所有数字 URL 的解决方案。因此上面的 URL 示例路由到 _40apples 控制器,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 或更高版本,则效果很好。

然后您将向您的控制器添加类似于此的属性路由:

[RoutePrefix("40apples")]

然后是每个特定操作的另一条路线:

[Route("{Buy}")]

不要忘记将 routes.MapMvcAttributeRoutes(); 添加到您的路由配置中。