Handle 404 exceptions in EPiServer CMS
As many of you know, there is a comprehensive 404 handler available for download through EPiCode. However, I just wanted a simple way of specifying a PageID and have that page act as a 404 response.
Easier said than done it seems
I actually got my 404 handler to work perfectly on my development machine - but that's because IIS 5 (the IIS version in Windows XP) allows wildcard mappings for all MIME types. IIS 6 (in Windows Server 2003) doesn't. Unless you modify the IIS metabase that is. I chose not to do so.
I'm halfway there
I urgently needed a decent 404 page which would display a pretty error message as well as a sitemap when an incorrect URL was requested. Most 404:s on the website were caused by requests for pages on an old replaced web site which didn't use friendly URL, so I could count on those requests to include the .aspx file extension - meaning they would be properly handled by IIS.
I'll do it myyyy - waaaaaay
I've stripped down this code from the global.asax.cs file to prove the concept, so you may want to complement it:
protected void Application_Error(object sender, EventArgs e)
{
//Get the last error that occured
HttpException ex =
(HttpException)HttpContext.Current.Server.GetLastError();
string redirectUrl;
//Get the HTTP code describing the type of error that occured
switch (ex.GetHttpCode())
{
case 404: //If a 404 error occured
int.TryParse(
ConfigurationManager.AppSettings["404PageId"],
out redirectPageId);
if (redirectPageId > 0)
redirectUrl =
ToolBox.GetFriendlyURL(redirectPageId);
break;
case 500: //If a server exception occured
int.TryParse(
ConfigurationManager.AppSettings["500PageId"],
out redirectPageId);
if (redirectPageId > 0)
redirectUrl =
ToolBox.GetFriendlyURL(redirectPageId);
break;
}
if(redirectUrl!=null) //A redirect URL exists
{
Response.StatusCode = 301;
Response.RedirectLocation = redirectUrl;
Response.End();
Server.ClearError();
}
}
Only triggered for ASP.NET requests
The Application_Error() method will execute properly for all requests handled by .NET - such as those for .aspx files. However, invalid friendly URL requests will not be handled by .NET and will therefore not trigger the error event.
I'm pretty sure there's a way to get this to work properly for invalid friendly URLs without running IIS 5, modifying the IIS 6 metabase or running IIS 7 on Windows Server 2008 - I just haven't found it yet... Any suggestions?
Update: Another solution is to use ASP.NET error handling. Check out my post on programmatically configuring customErrors to see how you could set error redirects to EPiServer pages.
07 February 2008