MVC中的多语言支持

时间:2016-04-06 04:01:23

标签: c# asp.net-mvc cookies routing multilingual

我有一个具有多语言功能的网站。我仍然使用cookie来检测语言,例如,如果用户选择"英语",那么我会将cookie值更改为" EN"并提供英文页面"给用户。

我想更改此行为并从URL而不是cookie中读取语言。例如,如果产品页面的当前网址是

www.ezstore.com/product/asus-gtx970

我想将网址更改为

www.ezstore.com/en/product/asus-gtx970 for english
www.ezstore.com/fr/product/asus-gtx970 for french

我正在考虑更改RouteConfig并阅读网址以获取语言值。这可能吗?

我当前的RouteConfig是:

routes.MapRoute("Product", "Product/{id}", new {
    controller = "Product",
    action = "Index",
    id = UrlParameter.Optional
});

routes.MapRoute(name: "Default", url: "{controller}/{action}/{id}", defaults: new {
    controller = "Home",
    action = "Index",
    id = UrlParameter.Optional
});

1 个答案:

答案 0 :(得分:1)

您可以更改自定义路线,如下所示: -

routes.MapRoute("Product", "{langcode}/Product/{id}", new {
    controller = "Product",
    action = "Index",
    id = UrlParameter.Optional
});

此处langcode将是语言的路由参数。

然后在控制器操作上获取langcode路由参数,如下所示: -

public ActionResult Index(string langcode)
{....}