Last active
August 29, 2015 14:06
-
-
Save ToJans/c4a3dfec30614c1741a0 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Collections.Generic; | |
using System.Globalization; | |
using System.Linq; | |
using System.Threading; | |
using System.Web; | |
using System.Web.Mvc; | |
using System.Web.Routing; | |
namespace Pauwels.AspNet | |
{ | |
public class RouteConfig | |
{ | |
public static void RegisterRoutes(RouteCollection routes) | |
{ | |
routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); | |
routes.MapRoute( | |
"Localized", | |
"{language}/{controller}/{action}/{id}", | |
new { language = LocalizedRouteHandler.DefaultLanguage, controller = "Home", action = "Index", id = "" }, | |
constraints: new { language = LocalizedRouteHandler.LanguageConstraint } | |
); | |
routes.MapRoute( | |
name: "NonLocalized", | |
url: "{controller}/{action}/{id}", | |
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional, language = LocalizedRouteHandler.DefaultLanguage } | |
); | |
} | |
} | |
class LocalizedRouteHandler : MvcRouteHandler | |
{ | |
static string[] AvailableLanguages = "nl fr de".Split(' '); | |
public static string DefaultLanguage = AvailableLanguages.First(); | |
public static string LanguageConstraint = String.Join("|",AvailableLanguages); | |
static Dictionary<string, CultureInfo> Cultures = | |
AvailableLanguages | |
.Select(x => CultureInfo.CreateSpecificCulture(x)) | |
.ToDictionary(x => x.TwoLetterISOLanguageName); | |
protected override IHttpHandler GetHttpHandler(RequestContext requestContext) | |
{ | |
var currentLanguage = requestContext.RouteData.Values["language"].ToString().ToLower(); | |
var currentCulture = AvailableLanguages.Contains(currentLanguage) ? Cultures[currentLanguage] : Cultures[DefaultLanguage]; | |
Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = currentCulture; | |
return base.GetHttpHandler(requestContext); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment