404 Handlers

April 13 2010

I'm currently thinking about how I'm going to approach my first Umbraco website.  I know I want to go with ASP.NET MVC, for better testability, but Umbraco is currently ASP.NET Web Forms only.  In my investigations I learnt about an interesting technique for getting around this problem: 404 handlers.

When a web page is requested, the server tries to map the request Url to a page.  When it comes up with nothing, a 404 (Page not found) error is returned.  In essence, the 404 Handler then performs custom actions, which include trying to find the page somewhere else.  In this case, that somewhere else is the Umbraco site.  The 404 handler can retrieve the CMS page and return the results in the response.

[DefaultAction("index")]
public class RescuesController : SmartDispatchController
{
private static readonly Regex headtitleRegex = new Regex("<h1>([^<]*)</>>");

public RescuesController(IApplicationContextProvider currentCustomerProvider, IConfigurationManager configurationManager) : base(currentCustomerProvider, configurationManager) { }

public void Index()
{
RenderView("rescues","content");

string pageName = Request.Uri.LocalPath;
if (pageName.EndsWith("/index"))
pageName = pageName.Substring(0, pageName.LastIndexOf("/index"));

try
{
var remoteContent = GetRemoteContent(pageName);

var matches = headtitleRegex.Match(remoteContent);
if (matches.Groups.Count > 1)
PropertyBag.HeadTitle = matches.Groups[1].Captures[0].Value;

PropertyBag.remoteContent = headtitleRegex.Replace(remoteContent, "");
} catch (WebException) {
Handle404();
}
}

public static string GetRemoteContent(string pageName)
{
return (new WebClient()).DownloadString("http://content.mysite.com/" + pageName);
}
}

CSS in our ASP.NET MVC site can be used to render the content.

Post a comment

comments powered by Disqus