ASP.NET MVC 3中的多语言URL - 避免使用多语言URL中的默认语言代码

时间:2012-03-02 20:57:24

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

我想为我的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"网址打开测试视图时,我会在浏览器中看到:

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

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

这就是我需要的东西

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

/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” - 它没有帮助。

我最终可能会将语言添加到所有网址,但我希望使用默认(“en”)语言的网址省略URL中的语言,如果有人通过“en” - 则重定向到没有语言的网址, 当为“en”生成URL时,URL不应包含它。

做这种事的正确方法是什么?

谢谢。

2 个答案:

答案 0 :(得分:1)

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

@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

答案 1 :(得分:0)

您可能需要的是Localization属性。有关详细信息,请参阅此帖子:

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