我有一个ASP.Net MVC应用程序,具有以下路由映射:
context.MapRoute("Empty","", new { controller = "Home", action = "Index" });
context.MapRoute("Info","/Info", new { controller = "Info", action = "Index" });
context.MapRoute("Base","/Info/Base", new { controller = "Info", action = "Base" });
我需要将一个语言前缀添加到URL作为段,以便URL看起来像这样:
www.something.com/en
www.something.com/en/Info
www.something.com/en/Info/Base
我通过将一个languageCode参数添加到URL轻松实现它:
context.MapRoute("Empty","/{languageCode}", new { controller = "Home", action = "Index" });
context.MapRoute("Info","/{languageCode}/Info", new { controller = "Info", action = "Index" });
context.MapRoute("Base","/{languageCode}/Info/Base", new { controller = "Info", action = "Base" });
不幸的是,这个参数应该是可选的。但是当我在这些路线下的URL中错过它时 - 我有404错误。
有什么想法如何实现呢?添加languageCode = UrlParameter.Optional没有帮助,只有当可选参数是尾随URL时才有效。
添加两个路由配置(使用和不使用languageCode
),您将获得所需的行为
context.MapRoute("Empty","/{languageCode}", new { controller = "Home", action = "Index" });
context.MapRoute("Info","/{languageCode}/Info", new { controller = "Info", action = "Index" });
context.MapRoute("Base","/{languageCode}/Info/Base", new { controller = "Info", action = "Base" });
context.MapRoute("Empty","", new { controller = "Home", action = "Index" });
context.MapRoute("Info","/Info", new { controller = "Info", action = "Index" });
context.MapRoute("Base","/Info/Base", new { controller = "Info", action = "Base" });
注意
以下配置与您的配置相同,但包含较少的配置代码(但它也会公开所有其他控制器)
routes.MapRoute(
name: "LanguageCode",
url: "{languageCode}/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index" }
);