Skip to content

Instantly share code, notes, and snippets.

@dampee
Last active April 11, 2016 08:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dampee/ae342a9b25edcce84902ea1a0d2b68fb to your computer and use it in GitHub Desktop.
Save dampee/ae342a9b25edcce84902ea1a0d2b68fb to your computer and use it in GitHub Desktop.
LastChanceContentFinder (404 not found for umbraco)
public class MyApplicationEvents : ApplicationEventHandler
{
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentLastChanceFinderResolver.Current.SetFinder(new MyLastChanceContentFinder());
}
}
using umbraco.cms.businesslogic.web;
using Umbraco.Web;
using Umbraco.Web.Routing;
/// <summary>
/// Acts as the 404 content finder for the website. If the requester url fails all other default Umbraco content finders, this one kicks in.
/// It must be registered in the application events with ContentLastChanceFinderResolver.Current.SetFinder(new MyLastChangeContentFinder());
/// Because this is the last chance content finder, it will ALWAYS return a 404.
/// </summary>
public sealed class MyLastChanceContentFinder : IContentFinder
{
public bool TryFindContent(PublishedContentRequest contentRequest)
{
if (!contentRequest.HasDomain)
return false;
var contentCache = contentRequest.RoutingContext.UmbracoContext.ContentCache;
int? rootContentId = contentRequest.UmbracoDomain.RootContentId;
if (rootContentId == null)
{
return false;
}
var domainRoot = contentCache.GetById(rootContentId.Value);
var segments = contentRequest.Uri.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
if (!segments.Any())
{
return false;
}
var firstSegment = segments.FirstOrDefault();
var root = domainRoot.Children.FirstOrDefault(x => x.UrlName == firstSegment);
root = root ?? domainRoot.Children.First();
var page = root.Descendants().FirstOrDefault(x => x.DocumentTypeAlias == My.Constants.DocumentTypes.NotFound.Alias );
if (page == null) return false;
contentRequest.PublishedContent = page;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment