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?
asked Feb 28, 2012 at 16:43
JuChom
6,0998 gold badges53 silver badges88 bronze badges
-
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.Steve Martin– Steve Martin2012年02月28日 17:17:31 +00:00Commented 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– JuChom2012年02月28日 17:33:11 +00:00Commented Feb 28, 2012 at 17:33
1 Answer 1
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());
}
answered Feb 28, 2012 at 17:39
tugberk
58.7k71 gold badges252 silver badges342 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-cs