Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ContentFinder for multilingual sites in Umbraco
using System;
using System.Globalization;
using System.Web;
using Umbraco.Web.Routing;
using Umbraco.Core;
public class MultilingualContentFinder : IContentFinder
{
public bool TryFindContent(PublishedContentRequest contentRequest)
{
try
{
var path = contentRequest.Uri.GetAbsolutePathDecoded();
var parts = path.Split(new[] { '/' }, System.StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) // redirect if root based on User Language
{
if (HttpContext.Current != null &&
HttpContext.Current.Request.UserLanguages != null &&
HttpContext.Current.Request.UserLanguages.Length > 0)
{
foreach (var x in HttpContext.Current.Request.UserLanguages)
{
if (x.StartsWith("es"))
{
contentRequest.SetRedirect("/es");
break;
}
if (x.StartsWith("en"))
{
contentRequest.SetRedirect("/en");
break;
}
}
}
if (!contentRequest.IsRedirect)
contentRequest.SetRedirect("/en"); // default to /en
}
switch (parts[0])
{
case "en" :
contentRequest.Culture = new CultureInfo("en-US");
break;
case "es":
contentRequest.Culture = new CultureInfo("es-US");
break;
default:
return false; // if path doesn't start with 'en' or 'us', then not found
}
string route = "/" + (parts.Length > 1 ? String.Join("/", parts, 1, parts.Length - 1) : "");
contentRequest.PublishedContent = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetByRoute(route, true);
}
catch (Exception ex)
{
Umbraco.Core.Logging.LogHelper.Error<MultilingualContentFinder>("MultilingualContentFinder exception", ex);
}
return contentRequest.PublishedContent != null;
}
}
using Umbraco.Core;
using Umbraco.Web.Routing;
public class RegisterEvents : ApplicationEventHandler
{
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentFinderResolver.Current.Clear();
ContentFinderResolver.Current.InsertType<ContentFinderByNotFoundHandlers>();
ContentFinderResolver.Current.InsertTypeBefore<ContentFinderByNotFoundHandlers, MultilingualContentFinder>();
}
}

naepalm commented Jan 6, 2016

Thanks for this, Alex. It was super useful for me :)

hey Alex, I'm using this as well. Do you have a way that i can exclude the Umbraco preview? I can't seems to get it to work with the preview button (it's showing 404)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment