0

I have a site with multi-language features. I'm still using cookie to detect the language so for example if user choose "English", then I will change the cookie value to "EN" and serve "english page" to user.

I want to change this behavior and read the language from URL instead of cookie. So for example if the current url for product page is

www.ezstore.com/product/asus-gtx970

I want to change the url to

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

I was thinking of changing the RouteConfig and read the URL to get the language value. Is this possible?

My current RouteConfig is :

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
});
tickwave
  • 3,335
  • 6
  • 41
  • 82
  • I would consider using the HTTP_ACCEPT_LANGUAGE header sent by the browser. That's the language the user prefers. – Poul Bak Apr 06 '16 at 04:12
  • Look at [this](http://www.wiliam.com.au/wiliam-blog/web-design-sydney-using-mvc-routing-for-seo-friendly-urls-on-multilingual-sites) article. – Jeroen Heier Apr 06 '16 at 04:16
  • I think this is the answer you need [http://stackoverflow.com/questions/1712167/asp-net-mvc-localization-route#answer-1712320](http://stackoverflow.com/questions/1712167/asp-net-mvc-localization-route#answer-1712320) – Ankush Jain Apr 06 '16 at 04:17
  • Possible duplicate of [ASP.NET MVC 5 culture in route and url](http://stackoverflow.com/questions/32764989/asp-net-mvc-5-culture-in-route-and-url) – NightOwl888 Apr 06 '16 at 06:00

1 Answers1

1

You can change your custom route as shown :-

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

Here langcode will be a route parameter for language.

and then get the langcode route parameter on controller action as shown:-

public ActionResult Index(string langcode)
{....}
Kartikeya Khosla
  • 18,743
  • 8
  • 43
  • 69
  • I actually have alot `MapRoute` in my `RouteConfig`, does that mean I need to add `{langcode}` in every `MapRoute`? Or is there a more efficient solution? – tickwave Apr 06 '16 at 04:13
  • @warheat1990...Yes..on which ever pages you want `langcode` in the url you have to change their routes as shown in answer. – Kartikeya Khosla Apr 06 '16 at 04:16