【问题标题】:Multilingual URLs in ASP.NET MVC 3 - avoid default language code in multilingual URLsASP.NET MVC 3 中的多语言 URL - 避免多语言 URL 中的默认语言代码
【发布时间】:2012-03-21 08:48:49
【问题描述】:

我想为我的 ASP.NET MVC 3 项目创建多语言 URL。

非默认语言应在 URL 中作为第一个参数使用路由传递。喜欢 /es/blog/some-blog-post-slug

英语将被用作默认语言,并且不需要在 URL 中传递语言。喜欢 /blog/some-blog-post

我尝试通过路由来实现,但是路由中断或 URL 生成。

我尝试了很多路由选项,包括自定义路由。 目前我有:

routes.MapRoute(
"", // Route name
"{lang}/{controller}/{action}/{slug}", // URL with parameters
new { controller = "Test", action = "Index", slug = UrlParameter.Optional }, // Parameter defaults
new { lang = "^[a-z]{2}$" }
);

routes.MapRoute(
"", // Route name
"{controller}/{action}/{slug}", // URL with parameters
new { controller = "Test", action = "Index", slug = UrlParameter.Optional } // Parameter defaults
);

在我的测试视图中,我有:

@Url.RouteUrl(new { controller = "Test", action = "Details", slug = "some-blog-post-slug" })
<br />
@Url.RouteUrl(new { lang = "es", controller = "Test", action = "Details", slug = "some-blog-post-slug" })

当我从浏览器中看到的"http://localhost:19038/test/details/my-blog-post-one" URL 打开测试视图时:

/Test/Details/some-blog-post-slug 

/es/Test/Details/some-blog-post-slug

这正是我所需要的

但是当我从"http://localhost:19038/es/test/details/my-blog-post-one" URL 打开测试视图时,我看到生成了不同的 URL:

/es/Test/Details/some-blog-post-slug 

/es/Test/Details/some-blog-post-slug

当我打开"http://localhost:19038/en/test/details/my-blog-post-one" 时,我得到:

/en/Test/Details/some-blog-post-slug 

/es/Test/Details/some-blog-post-slug

"http://localhost:19038/xx/test/details/my-blog-post-one" 产生:

/xx/Test/Details/some-blog-post-slug 

/es/Test/Details/some-blog-post-slug

为什么要附加“xx”?我没有将语言传递给 Razor HTML URL 帮助程序。 我还尝试在控制器的默认参数中使用 lang = "en" - 它没有帮助。

我最终可以将语言添加到所有 URL,但我希望使用默认 (“en”) 语言的 URL 省略 URL 中的语言,并且即使有人传递“en” - 重定向到没有语言的 URL , 当为“en” URL 生成 URL 时,不应包含它。

这样做的正确方法是什么?

谢谢。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 asp.net-mvc-routing


    【解决方案1】:

    当您访问 /xx/Test/Details/some-blog-post-slug 时,ASP.NET MVC 3 将带有值 xx{lang} 添加到路由数据中,并且在您调用时会考虑到这一点:

    @Url.RouteUrl(new { controller = "Test", action = "Details", slug = "some-blog-post-slug" })
    

    如果你指定

    @Url.RouteUrl(new { lang = (string)null, controller = "Test", action = "Details", slug = "some-blog-post-slug" })
    

    然后它通过使用缺少lang 的备用路由来呈现您期望的值,从而导致:

    /Test/Details/some-blog-post-slug
    

    【讨论】:

    • 我现在正在使用这种方法。还没找到更好的。
    【解决方案2】:

    您可能想要的是一个本地化属性。详情请看这篇文章:

    geekswithblogs.net/shaunxu/archive/2010/05/06/localization-in-asp.net-mvc-ndash-3-days-investigation-1-day.aspx

    【讨论】:

      猜你喜欢
      • 2021-09-24
      • 2011-06-19
      • 2011-07-13
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2013-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多