Written by
Per Ploug Hansen
For umbraco versions:
AllReference
Not found handlers are used to present alternative content when a url doesn't return a page. This will go through the standard handlers and show how to create and setup your own.
Okey finally getting to the code. In this case I wanted to have a seperate 404 page for each site - which had it's own domain.
Each site had a Top node which took care of some general site values like title, some meta, and the ID of the 404 page. The ID of the 404 was set with a content picker, with the alias "NotFoundPage"
So to get a custom page for a specific URL I wrote the follow handler:
using System;
using System.Xml;
using System.Xml.XPath;
using System.Web;
using umbraco;
using umbraco.cms.businesslogic.web;
using umbraco.interfaces;
namespace MyCustomHandler {
public class NotFoundHandler : INotFoundHandler {
private int _redirectID = -1;
#region INotFoundHandler Members
public bool CacheUrl {
get {
return false;
}
}
public bool Execute(string url) {
bool _succes = false;
string currentDomain = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
int rootNodeID = Domain.GetRootFromDomain(currentDomain);
try {
if (rootNodeID > 0) {
string errorID = new umbraco.presentation.nodeFactory.Node(rootNodeID).GetProperty("NotFoundPage").Value;
if (errorID != "") {
_redirectID = int.Parse(errorID);
_succes = true;
}
}
} catch {
_succes = false;
}
return _succes;
}
public int redirectID {
get {
return _redirectID;
}
}
#endregion
}
}
What You should notice:
It uses the INotFoundHandler interface, where all the interesting stuff happens in the execute(url) area. In this case we take the current domain, and get's it root node ID with Domain.GetRootFromDomain(domain) which returns the ID of the node with domain attached.
Afterwards we use the standard nodefactory to fetch the Property "NotFoundPage" to fetch the ID of our custom error page.
If all goes well we set the redirectID to this and set success to "true", this means that Umbraco will display the content of the page with our NotFoundPage ID instead.
If not we set it to "false" and let umbraco continue to the next 404 Handler, because this one was not successfull in finding an alternative page.
The only limitation on the handler is that you cannot redirect to a specific url. You can only return a Node ID which umbraco will then process.