[英]ASP.NET MVC routing URLs starting with numbers
Obviously in C# classes are not allowed to start with a number so how do I create controllers for URLs that start with a number in ASP.NET 4.6? 显然,在C#中,类不允许以数字开头,因此如何为ASP.NET 4.6中以数字开头的URL创建控制器?
Example URL: 范例网址:
www.domain.com/40apples/
EDIT: Routing each URL individually will quickly become a pain to manage. 编辑:单独路由每个URL将很快变得难以管理。 Ideally, I'm looking for a solution that handles all number URLs.
理想情况下,我正在寻找一种可以处理所有数字URL的解决方案。 So that the above URL example routes to _40apples controller, 300cherries to _300cherries and 1orange to _1orange
因此,上述网址示例将路由到_40apples控制器,300樱桃到_300樱桃以及1orange到_1orange
You will have to use custom routing, in your RegisterRoutes method you could add another route that looks something like this: 您将必须使用自定义路由,在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
);
}
If you would want your route to catch anything starting with a number + apples you could use a regex-constraint. 如果您希望自己的路线捕获以数字+苹果开头的所有内容,则可以使用正则表达式约束。 Something like this:
像这样:
routes.MapRoute(
"ApplesRoute", // Route name
"{number}apples/{action}", // URL with parameters
new { controller = "Apples", action = "Index" } // Parameter defaults
,new {number = @"\d+" } //constraint
);
An even more generic approach would be to catch all routes that starts with a number + a word. 更为通用的方法是捕获以数字+单词开头的所有路由。 Then you could build your route and constraints something like this:
然后,您可以构建路线和约束,如下所示:
routes.MapRoute(
"NumbersRoute", // Route name
"{numberfruit}/{action}", // URL with parameters
new { controller = "Numbers", action = "Index" } // Parameter defaults
,new { numberfruit = @"\d+[A-Za-z]" } //constraint
);
EDIT after discussion with Organic: 与Organic讨论后编辑:
The approach that solved the problem in this case was using attribute routing. 解决这种情况的方法是使用属性路由。 Which works well if you're using mvc 5 or greater.
如果您使用的是mvc 5或更高版本,则效果很好。
Then you would add an attribute route similar to this to your controller: 然后,您可以向控制器添加与此类似的属性路由:
[RoutePrefix("40apples")]
And then another route to every specific action: 然后是执行每个特定操作的另一条路线:
[Route("{Buy}")]
Do not forget to add routes.MapMvcAttributeRoutes();
不要忘记添加
routes.MapMvcAttributeRoutes();
to your route config. 到您的路由配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.