我想要一条路线,它提供两个 URL 选项,但映射到一个操作。一个很好的例子是多语言应用程序。让我们以英语和法语为例。
乍一看这似乎很简单,从技术上讲你可以做到:
routes.MapRoute(
"the hi route english" ,
"welcome/sayhi/{id}" ,
new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional }
);
routes.MapRoute(
"the hi route french" ,
"bienvenu/direallo/{id}" ,
new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional }
);
但这意味着您必须为每个操作定义两条路线。或者更好的解决方案,创建一个自定义 Route 类,它需要更多参数来处理双语。
如果我选择选项 1 或 2,这意味着我必须定义 WelcomeController 的每条路由,因为我不能在我的路由中使用 {action}。
理想情况下,我希望能够通过元数据至少定义操作名称,然后通过反射或其他方式获取它。
即:
[ActionName( { "fr", "direallo" }, {"en", "sayhi"})]
public ActionResult SayHi(string id){
//check current thread culture...
}
我不太确定从哪里开始,有什么想法吗?提示?
谢谢,
最佳答案
这里有几种选择的起点,大致是(按照实现复杂度的顺序):
- 每种语言的路线(如上所述)
-
routes.MapRoute( "the hi route", "{controllerName}/{actionName}/{id}", new { controller = "Welcome" , action = "SayHi" , id = UrlParameter.Optional }, new { controllerName = @"welcome|bienvenu", actionName = @"sayhi|direallo" } );
您可以创建一个基本 Controller ,它由每种语言的子类继承,并为每个基本 Controller 操作方法定义一个语言特定的操作名称
- 您可以创建自己的(或使用 one 中提供的 answer 到 Justin Pihony 的评论)自定义路由约束
关于c# - MVC 路由 : How to map two names to one action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9433146/