I’ve a multi-language site. I’m trying to change to english (including the URL) when the site doesn’t have the requested language. I want to do that by redirecting to the same page but changing the url’s language. So I added a resource with the key “_Language” which get the language code if it is active. For example if the resource file doesn’t exists or it does but it isn’t ready, it will fallback into some other language. In the global.asax I have this code:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"DefaultLang", // Route name
"{language}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
new { language = "^[a-z]{2}$" } // Get language
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Cuenta", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
public static string Language
{
get
{
var currentContext = new HttpContextWrapper(HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(currentContext);
if (routeData != null)
{
var lang = (string)routeData.Values["language"];
if (lang != null && lang.Length == 2)
return lang.ToLower();
}
return "es";
}
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(MvcApplication.Language);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(MvcApplication.Language);
if (Texts._Language != MvcApplication.Language) // Detect fallback.
{
Response.Redirect(Request.Url.AbsoluteUri.Replace("/" + MvcApplication.Language + "/", "/en/"));
Response.End();
return;
}
}
My problem is that for some reason each time the user is redirected by the BeginRequest the response its a 404. I’ve compared the url with the one when the language is set (from the beginning) in english and they are the same! Why is this happening?
How stupid! I was actually doing this with a POST request =(