Created
September 15, 2012 16:44
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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