Last active
April 11, 2016 08:12
-
-
Save dampee/ae342a9b25edcce84902ea1a0d2b68fb to your computer and use it in GitHub Desktop.
LastChanceContentFinder (404 not found for umbraco)
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
public class MyApplicationEvents : ApplicationEventHandler | |
{ | |
protected override void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) | |
{ | |
ContentLastChanceFinderResolver.Current.SetFinder(new MyLastChanceContentFinder()); | |
} | |
} |
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 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