在 ASP.NET MVC 中,是否可以定义路由,根据 URL 部分的数据类型来确定使用哪个 Controller ?
例如:
routes.MapRoute("Integer", "{myInteger}", new { controller = "Integer", action = "ProcessInteger", myInteger = "" });
routes.MapRoute("String", "{myString}", new { controller = "String", action = "ProcessString", myString = "" });
本质上,我希望以下 URL 由不同的 Controller 处理,即使它们具有相同数量的部分:
mydomain/123
mydomain/ABC
附言上面的代码不起作用,但它表明了我想要实现的目标。
最佳答案
是的,如果你使用 constraints :
像这样:
routes.MapRoute(
"Integers",
"{myInteger}",
new { controller = "Integer", action = "ProcessInteger"},
new { myInteger = @"\d+" }
);
如果将该路由放在字符串路由之上(不包含 @"\d+"
的约束),那么它会过滤掉所有包含整数的路由,以及任何不包含整数的路由'有整数将被传递,你的 string
路由将拾取它。
真正的诀窍是路由可以根据 Regular Expressions 过滤通过的内容,这就是您如何确定应该拾取它的方式。
关于c# - ASP.NET MVC URL 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1165322/