Last active
August 9, 2018 13:01
-
-
Save DanDiplo/b0ea3a6d304a7fde755eca0431509bd0 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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using Umbraco.Web.Routing; | |
namespace Diplo.Core | |
{ | |
/// <summary> | |
/// Umbraco content finder implementation for 404 pages in multi-lingual sites | |
/// Assumes each site has a document type with alias of "PageNotFound" in the root of the site (under home node) | |
/// </summary> | |
public class FourOhFourFinder : IContentFinder | |
{ | |
/// <summary> | |
/// Used to find the correct 404 page when a page cannot be found in Umbraco | |
/// </summary> | |
/// <param name="contentRequest">The current Umbraco context</param> | |
/// <returns>The 404 page</returns> | |
public bool TryFindContent(PublishedContentRequest contentRequest) | |
{ | |
//Check request cannot be found | |
if (contentRequest.PublishedContent == null) | |
{ | |
var domain = contentRequest.Domain; | |
if (domain != null) | |
{ | |
var home = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(domain.RootNodeId); | |
if (home != null) | |
{ | |
//Get the 404 node | |
var notFoundNode = home.Children.FirstOrDefault(x => x.DocumentTypeAlias == "PageNotFound"); | |
if (notFoundNode != null) | |
{ | |
//Set Response Status to be HTTP 404 | |
contentRequest.SetResponseStatus(404, "404 Page Not Found"); | |
//Set the node to be the not found node | |
contentRequest.PublishedContent = notFoundNode; | |
} | |
} | |
} | |
} | |
return contentRequest.PublishedContent != null; | |
} | |
/// <summary> | |
/// Also need to register the handler in OnApplicationStarting | |
/// </summary> | |
public void ApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) | |
{ | |
ContentFinderResolver.Current.InsertTypeBefore<ContentFinderByNotFoundHandlers, Diplo.Core.FourOhFourFinder>(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment