Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 15, 2012 16:44
Show Gist options
  • Save davybrion/3728767 to your computer and use it in GitHub Desktop.
Save davybrion/3728767 to your computer and use it in GitHub Desktop.
code snippets for "Automatically Including Current Language In Generated URLs With ASP.NET MVC" post
public class AutoLocalizingRoute : Route
{
public AutoLocalizingRoute(string url, object defaults, object constraints)
: base(url, new RouteValueDictionary(defaults), new RouteValueDictionary(constraints), new MvcRouteHandler()) { }
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
{
// only set the culture if it's not present in the values dictionary yet
// this check ensures that we can link to a specific language when we need to (fe: when picking your language)
if (!values.ContainsKey("language"))
{
values["language"] = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
}
return base.GetVirtualPath(requestContext, values);
}
}
var localizingRoute = new AutoLocalizingRoute("{language}/{controller}/{action}/{id}",
new { id = UrlParameter.Optional }, new { language = "^[a-z]{2}$" });
RouteTable.Routes.Add("LocalizingRoute", localizingRoute);
RouteTable.Routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
private void OnBeginRequest(object sender, EventArgs e)
{
var currentContext = new HttpContextWrapper(HttpContext.Current);
var routeData = RouteTable.Routes.GetRouteData(currentContext);
if (routeData == null || routeData.Values.Count == 0) return;
if (routeData.Values["language"] == null)
{
RedirectToUrlWithAppropriateLanguage(currentContext, routeData);
}
var languageCode = (string)routeData.Values["language"];
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(languageCode);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(languageCode);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment