Last active
October 14, 2015 15:58
-
-
Save dampee/71044d500a0f04873c2b to your computer and use it in GitHub Desktop.
Umbraco ContentLastChanceFinder for 404 pages
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.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