【问题标题】:Asp.Net MVC MapRoute with optional language URL segment带有可选语言 URL 段的 Asp.Net MVC MapRoute
【发布时间】:2019-07-24 15:32:59
【问题描述】:

我有一个带有以下路由映射的 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 时才有效。

【问题讨论】:

    标签: asp.net url routing segment


    【解决方案1】:

    添加两个路由配置(有和没有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" }
    );
    

    【讨论】:

    • 谢谢,非常有帮助。我的问题是订购 MapRoutes。每个“语言定义”后面都应有“非语言定义”。
    猜你喜欢
    • 2010-12-07
    • 2011-06-19
    • 2015-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 2013-11-17
    相关资源
    最近更新 更多