I am working on an MVC site that will have multiple translations. We want to do this through subdomains such as http://en.domain.com or http://fr.domain.com . We also want to maintain a regular domain of http://domain.com .
Translations work provided that you change the subdomain manually, but Iβm looking for a way to automate this and maintain the entire current URL to allow the user who finds http://en.domain.com/product to click on the link and get a different language version the same page. It seems simple to simply highlight the subdomain, if it exists, separate it from the current URL and replace the specified version of the language.
Essentially:
http://en.domain.com/product (original)
http://domain.com/product (cleared)
http://fr.domain.com/product or http://de.domain.com/product etc. (output)
I started looking for built-in functions like Request.Url.Subdomain , but came to the conclusion that there is no such magical creature. Then I moved on to basic string manipulation, but it seemed really confusing, so I went off to look for a solution to regular expressions.
I tested this regex with some online testers that usually work for me, and they correctly identify the subdomain when it exists, but cannot find the result when the code really works.
I use regular expressions a bit and I hope there is something really obvious that I'm doing wrong here. If there is a better solution, I am open to other implications.
WITH#
string url = Request.Url.AbsoluteUri; //http://en.domain.com/ Regex regex = new Regex(@"/(?:http[s]*\:\/\/)*(.*?)\.(?=[^\/]*\..{2,5})/", RegexOptions.IgnoreCase); GroupCollection results = regex.Match(url).Groups; Group result = results[0];
Here is the solution I have now. Not as elegant as we would like, but for something that ate too much time, now it works as intended.
View
<a href="@Html.Action("ChangeLanguage", new { lang = "en" })">English</a> <a href="@Html.Action("ChangeLanguage", new { lang = "fr" })">French</a>
Act
public string ChangeLanguage(string controller, string lang) { string url = Request.Url.AbsoluteUri; Regex regex = new Regex(@"(?:https*://)?.*?\.(?=[^/]*\..{2,5})", RegexOptions.IgnoreCase); GroupCollection results = regex.Match(url).Groups; Group result = results[0]; if (result.Success) { string[] resultParts = result.Value.Split('/'); string newSubDomain = resultParts[0] + "//" + lang + "."; url = url.Replace(result.Value, newSubDomain); } else { string[] urlParts = url.Split('/'); string oldParts = urlParts[0] + "//"; string newParts = urlParts[0] + "//" + lang + "."; url = url.Replace(oldParts, newParts); } return url; }