Is there any good method to create route rewriting for a multilingual web application?
The URL schema should be the following
http://<Domainname>/{Language}/{Controller}/{Action}/{Id}
but URLs without the Language part should also be supported, but they should not just map to the controllers directly but generate a redirect response.
The important thing here is that the redirect should not be hard coded to a specific language but be determined based on factors like the users preferred language if possible.
Note: The process of determining the correct language is not the problem, just how to do the non static rewriting.
Thanks
I managed that with following routes;
routes.MapRoute(
"Default", // Route name
"{language}/{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", language = "tr", id = UrlParameter.Optional }, // Parameter defaults
new { language = @"(tr)|(en)" }
);
I handle the culture by overriding the GetControllerInstance() method of DefaultControllerFactory. the example is below;
public class NinjectControllerFactory : DefaultControllerFactory {
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) {
//Get the {language} parameter in the RouteData
string UILanguage;
if (requestContext.RouteData.Values["language"] == null) {
UILanguage = "tr";
}
else {
UILanguage = requestContext.RouteData.Values["language"].ToString();
}
//Get the culture info of the language code
CultureInfo culture = CultureInfo.CreateSpecificCulture(UILanguage);
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
return base.GetControllerInstance(requestContext, controllerType);
}
}
and register it on the global.asax;
protected void Application_Start() {
//other things here
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With