Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Umbraco "Legacy URL" IContentFinder
using System;
using System.Web.Routing;
using Umbraco.Web;
using Umbraco.Web.Routing;
// as per http://maffrigby.com/using-custom-routes-in-umbraco/
namespace MyUmbraco
{
public class MyUmbracoApplication : UmbracoApplication
{
//protected override void OnApplicationStarted(object sender, EventArgs e)
//{
// base.OnApplicationStarted(sender, e);
// RouteConfig.RegisterRoutes(RouteTable.Routes);
//}
protected override void OnApplicationStarting(object sender, EventArgs e)
{
ContentFinderResolver.Current.RemoveType<ContentFinderByNotFoundHandlers>();
ContentLastChanceFinderResolver.Current.SetFinder(new MyContentFinder());
base.OnApplicationStarting(sender, e);
}
}
}
using Umbraco.Core;
using Umbraco.Core.Services;
using Umbraco.Web;
using Umbraco.Web.Routing;
using umbraco;
using System.Linq;
namespace MyUmbraco
{
// via https://creativewebspecialist.co.uk/2013/08/07/the-new-way-to-do-a-404-umbraco-handler/
public class MyContentFinder : IContentFinder
{
const int NOT_FOUND_NODE = 1111; // THIS IS THE NODE FOR MY 404 PAGE
const int REDIRECT_TYPE = 302; // TODO: Set to 301 for permanent/SEO purposes when you're more comfortable
const string LEGACY_URL_FIELD = "myLegacyUrl";
const string HOME_DOCTYPE = "myHomePage";
readonly string[] IGNORED_PATTERNS = new string[] { ".png", ".jpg", ".gif", ".pdf" };
public bool TryFindContent(PublishedContentRequest contentRequest)
{
//Check request is a 404
if (contentRequest.Is404)
{
var reqPath = contentRequest.Uri.AbsolutePath;
var notFoundNode = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(NOT_FOUND_NODE);
var home = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetAtRoot().Single(x => x.DocumentTypeAlias == HOME_DOCTYPE);
//(don't waste db search on asset requests etc)
if (!IGNORED_PATTERNS.Any(pattern => reqPath.Contains(pattern))) {
// search DB for legacy URL that matches content request
var reqPathSearch = reqPath.ToLowerInvariant().Replace("/", "");
var legacyNode = home.Descendants()
.DefaultIfEmpty(notFoundNode)
.Where(d=>d.HasProperty(LEGACY_URL_FIELD))
.FirstOrDefault(x =>
reqPathSearch == x.GetPropertyValue<string>(LEGACY_URL_FIELD).ToLowerInvariant().Replace("/", "").Replace(".aspx","").Replace(".htm","")
);
if(legacyNode != null && legacyNode != notFoundNode) {
// if we have one, do a redirect
contentRequest.SetRedirect(legacyNode.Url, REDIRECT_TYPE);
return contentRequest.PublishedContent != null;
}
}
// default to 404
contentRequest.SetResponseStatus(404, "404 Page Not Found");
contentRequest.PublishedContent = notFoundNode;
}
return contentRequest.PublishedContent != null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment