3

I'm creating a website with internationalization and what I want to do is to support URL with this format:

"{country}/{controller}/{action}"

How can I tell the routing engine that {country} should be set using a session variable?

2
  • Enquiry: If you are using the country in your route, why would you need to maintain it within session? You can use the route as a means of persisting the selected country through page requests thereby negating the need to use session to remember this. Feb 28, 2012 at 17:17
  • If someone connect to localhost/ {controller} = "Home", {Action} = "Index". But for {country} if the user comes from an english speaking country {country} = "en", from a spanish speaking country "es", from a french speaking country "fr" and so on. I thought storing the {country} in a session variable to reuse it, but I'm open to all suggestions.
    – JuChom
    Feb 28, 2012 at 17:33

1 Answer 1

3

You can do this with a custom Controller Factory. Start with your route:

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 LocalizedControllerFactory : 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);
    }

}

You can here get the value from session instead of hardcoding it as I did.

and register it on the Global.asax:

protected void Application_Start() {

    //...    
    ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.