Skip to content

Instantly share code, notes, and snippets.

@dampee
Last active October 14, 2015 15:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dampee/71044d500a0f04873c2b to your computer and use it in GitHub Desktop.
Save dampee/71044d500a0f04873c2b to your computer and use it in GitHub Desktop.
Umbraco ContentLastChanceFinder for 404 pages
using System;
using System.Globalization;
using System.Linq;
using umbraco.cms.businesslogic.web;
using Umbraco.Core;
using Umbraco.Web;
using Umbraco.Web.Routing;
/// <summary>
/// Summary description for NotFoundHandler
/// </summary>
public class NotFoundHandler : ApplicationEventHandler
{
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentLastChanceFinderResolver.Current.SetFinder(new My404ContentFinder());
}
}
public class My404ContentFinder : IContentFinder
{
public bool TryFindContent(PublishedContentRequest contentRequest)
{
if (!contentRequest.HasDomain)
return false;
var contentCache = contentRequest.RoutingContext.UmbracoContext.ContentCache;
var domainRoot = contentCache.GetById(contentRequest.Domain.RootNodeId);
var firstSegment = contentRequest.Uri.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).First();
var root = domainRoot.Children.FirstOrDefault(x => x.UrlName == firstSegment);
root = root ?? domainRoot.Children.First();
var page = root.Descendants().FirstOrDefault(x => x.DocumentTypeAlias == "404");
if (page == null) return false;
contentRequest.PublishedContent = page;
var wcd = Domain.GetDomainsById(root.Id, true).SingleOrDefault(x => x.IsWildcard);
if (wcd != null) contentRequest.Culture = new CultureInfo(wcd.Language.CultureAlias);
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment