I have an MVC4 application that has an extra element in the route/url, it’s named language:
routes.MapRoute(
name: "languageDefault",
url: "{language}/{controller}/{action}/{id}",
defaults: new {
language = "en-US",
controller = "Home",
action = "Index",
id = UrlParameter.Optional
}
);
Now, every time an action is done I check if the language is set correctly using a custom filterAttribute:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string cultureName = null;
var request = filterContext.HttpContext.Request;
string currentUrl = request.RawUrl;
string[] splittedStrings = currentUrl.Split('/');
string currentLanguage = CultureHelper.CheckCulture();
var cultureCookie = request.Cookies["_culture"];
var possibleCultures = UnitOfWork.CulturesRepository.GetListOfCultureNames();
foreach (string culture in possibleCultures)
{
if (splittedStrings[1] == culture) cultureName = splittedStrings[1];
}
if (cultureCookie != null) cultureName = cultureCookie.Value;
if (currentLanguage != null) cultureName = currentLanguage;
if (cultureName != null)
{
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
else
{
cultureName = possibleCultures[0];
Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(cultureName);
Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
}
base.OnActionExecuting(filterContext);
}
My problem now is that while I check if there is a language present and if there is not, set one, I don’t really do anything if the language provided isn’t correct. For example
When a user types:
http://www.example.com/en-US/shop
He has provided a correct url and thus will see the shop page correctly. However, if he does not provide a language like so:
http://www.example.com/shop
The check for the language is done, and depending on if this is his first visit or not, his language is set. The problem with this is that the url doesn’t change.
I’d like the url to be changed so that it shows the language in which the user views the page. In other words when trying to visit
http://www.example.com/shop
He should be redirected to:
http://www.example.com/en-US/shop
And this needs to happen regardless of which page the visitor visits. In other words I probably need to add something in either the global.asax or in the overrided function I provided.
But I don’t know what and how.
I’ve solved it by changing my OnActionExecuting method:
Now, when you fill in an incorrect language you are redirected to a page with a correct language, if you provide two incorrect parameters you are redirected to a 404 (which is logical).