I want to create multilingual URLs for my ASP.NET MVC 3 project.
Non-default language should be passed in URL as the first parameter using routing. Like /es/blog/some-blog-post-slug
English will be used as default language and require not to pass the language in URL. Like /blog/some-blog-post
I tried to do it with routing but either routing breaks or URL generation.
I tried many options with Routing, with custom routing. Currently I have:
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
);
In my test view I have:
@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" })
When I open the test view from "http://localhost:19038/test/details/my-blog-post-one" URL I see in my browser:
/Test/Details/some-blog-post-slug
/es/Test/Details/some-blog-post-slug
That's pretty much what I need
But when I open the test view from "http://localhost:19038/es/test/details/my-blog-post-one" URL I see different URL generated:
/es/Test/Details/some-blog-post-slug
/es/Test/Details/some-blog-post-slug
When I open "http://localhost:19038/en/test/details/my-blog-post-one" I get:
/en/Test/Details/some-blog-post-slug
/es/Test/Details/some-blog-post-slug
And "http://localhost:19038/xx/test/details/my-blog-post-one" produces:
/xx/Test/Details/some-blog-post-slug
/es/Test/Details/some-blog-post-slug
Why "xx" is appended? I don't pass a language to the Razor HTML URL helper. I also tried to use lang = "en" in controller's default parameters - it didn't help.
I could end up adding the language to all URLs, but I want the URLs with default ("en") language to omit the language in URL, and if even someone passing "en" - redirect to the URL without the language, and when URL is generated for "en" URL should not include it.
What is the right way to do such thing?
Thank you.