Skip to content

Instantly share code, notes, and snippets.

@leekelleher
Created March 5, 2014 13:57
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 leekelleher/9367600 to your computer and use it in GitHub Desktop.
Save leekelleher/9367600 to your computer and use it in GitHub Desktop.
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Logging;
using Umbraco.Web;
using Umbraco.Web.Routing;
namespace uComponents.ContentFinders
{
public class PageNotFoundContentFinder : IContentFinder
{
public bool TryFindContent(PublishedContentRequest contentRequest)
{
if (contentRequest == null)
return false;
LogHelper.Debug<PageNotFoundContentFinder>("TryFindContent({0})", () => contentRequest.Uri.ToString());
// get all the content nodes that have a property value for 'umbracoPageNotFound'
// sort them in descending order (by @level), then select the first one that has the closest URL/path.
var path = contentRequest.Uri.GetAbsolutePathDecoded();
var xpath = "descendant::*[@isDoc and normalize-space(umbracoPageNotFound)]";
var node = contentRequest
.RoutingContext
.UmbracoContext
.ContentCache
.GetByXPath(xpath, null)
.OrderByDescending(x => x.Level)
.FirstOrDefault(x => path.IndexOf(x.Url) >= 0);
if (node == null)
return false;
var pageNotFoundId = node.GetPropertyValue<int>("umbracoPageNotFound");
if (pageNotFoundId <= 0)
return false;
var pageNotFound = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(pageNotFoundId);
if (pageNotFound == null)
return false;
contentRequest.PublishedContent = pageNotFound;
contentRequest.SetIs404();
return true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment