2016-04-06 92 views
0

我有一個具有多語言功能的網站。我仍然使用cookie來檢測語言,例如,如果用戶選擇「英文」,那麼我會將cookie值更改爲「EN」並向用戶提供「英文頁面」。MVC中的多語言支持

我想更改此行爲並從URL而不是cookie中讀取語言。因此,例如,如果產品頁面當前URL是

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和讀取URL來獲得語言的價值。這可能嗎?

我現在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 
}); 
+0

我會考慮使用瀏覽器發送的HTTP_ACCEPT_LANGUAGE頭。這是用戶喜歡的語言。 –

+0

看看[this](http://www.wiliam.com.au/wiliam-blog/web-design-sydney-using-mvc-routing-for-seo-friendly-urls-on-multilingual-sites)文章。 –

+0

我認爲這是你需要的答案[http://stackoverflow.com/questions/1712167/asp-net-mvc-localization-route#answer-1712320](http://stackoverflow.com/questions/1712167/asp -net-mvc-localization-route#answer-1712320) –

回答

1

您可以更改您的自定義路線如下所示: -

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

這裏langcode將是語言的路由參數。

,然後得到控制行動langcode路線參數,如下所示: -

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

我實際上有''MapRoute'在我的'RouteConfig',這是否意味着我需要在每個'MapRoute'中添加'{langcode}'?還是有更高效的解決方案? – warheat1990

+0

@ warheat1990 ...是的..在網址中你想要'langcode'的網頁,你必須改變他們的路線,如答案中所示。 –