5

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

Fionn
  • 10,975
  • 11
  • 54
  • 84

1 Answers1

4

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());
}
tugberk
  • 57,477
  • 67
  • 243
  • 335
  • is there option not to have language for default locale / – GorillaApe Aug 15 '12 at 02:49
  • 1
    @Parhs you should handle that by ignoring the route so that it doesn't go inside the MVC pipeline. For example, this route ignores all the requests which has an extension of **ico**: `routes.IgnoreRoute("{*allico}", new { allico = @".*\.ico(/.*)?" });` – tugberk Aug 15 '12 at 07:23