Overwrite ASP.net MVC3 Multilingual Route

Is there any good way to create route rewriting for a multilingual web application?


URL scheme should be as follows

http://<Domainname>/{Language}/{Controller}/{Action}/{Id}

but URLs without part of the language should also be supported, but they should not just map directly to controllers, but generate a redirect response.

It is important that the redirection should not be hardcoded in a specific language, but is determined based on factors such as the user's preferred language, if possible.

Note. The process of determining the correct language is not a problem, just how to do non-stationary rewriting.

thank

+5
source share
1 answer

I managed this with the 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 process the culture by overriding the GetControllerInstance () method of DefaultControllerFactory. Below is an example:

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 global.asax;

protected void Application_Start() {

    //other things here


    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}
+4
source

All Articles