Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.