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

标签 c# asp.net .net asp.net-mvc asp.net-mvc-routing

显然在 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/

相关文章:

c# - 为什么这个方法接受字节,当它的参数是 double ?

c# - 比较枚举值进行排序

c# - 如何忽略/跳过/处理 HttpWebResponse 错误并仍然将 JSON 返回到我的代码?

关于大型项目中层分离的 ASP.Net 架构

c# - 从 aspnet5 引用 "old".NET 4.x DLL?

C# Msmq 错误 : (0x80004005): An invalid handle was passed to the function

.net - 如何使用命令行实用程序编辑 exe 的资源(文件描述、图标等)?

C#/MS Access : database connection errors

c# - 尝试从服务进行远程 WMI 调用时访问被拒绝

.net - asp.net mvc 可选参数