Created
March 5, 2014 13:57
-
-
Save leekelleher/9367600 to your computer and use it in GitHub Desktop.
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.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