我有一个具有以下路由映射的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
我可以通过向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" });
很遗憾,此参数应该是可选的。但是当我在这些路线下的URL中错过它时,我会遇到404错误。
任何想法如何实施?添加languageCode =UrlParameter。Optional无效,仅当可选参数为尾随URL时有效。
答案 0 :(得分:0)
添加两个路由配置(带有和不带有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" }
);