JuChom
JuChom

Reputation: 5999

How to set ASP.Net MVC Routing parameter

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?

Upvotes: 3

Views: 1902

Answers (1)

tugberk
tugberk

Reputation: 58494

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());
}

Upvotes: 3

Related Questions