EPiServerSeptember 9, 2009

“The current page is not of type MyPageType” exception when browsing with non-friendly URL

Yesterday we ran into a problem in the project that I’m currently working on. We’re using Page Type Builder and when we tried to view a page by going to it’s non-friendly URL, that is /HelloWorld.aspx?id=30 instead of /HelloWorld/, we got an exception thrown by Page Type Builder saying “The current page is not of type <PageTypeName>”.

An exception with that error message is thrown when using TemplatePage<PageType>, UserControlBase<PageType> or one of the other base classes for pages and controls in Page Type Builder and you are trying to access a page that isn’t of the specified page type. The problem in this case was that the page with the specified ID in the query string was of the correct page type.

It turns out that EPiServers friendly URL rewriter, for some to me mysterious reason, strips the ID-parameter from the query string collection even if it doesn’t do any actual rewriting. That in turn means that when someone tries to access PageBase.CurrentPageLink, which Page Type Builders above mentioned base classes does, the property will return PageReference.StartPage (which is the default) instead of the actually requested page. And since the start page isn’t of the requested type the exception is thrown.

Luckily we found simple a workaround posted in this thread by Tiberiu Covaci. The solution is to hook into the ConvertingToInternal event in the URL rewrite provider and cancel URL rewriting if the requested URL is for an ASPX-page. Modify your global.asax.cs to contain this:

protected void Application_Start(Object sender, EventArgs e)
{
    UrlRewriteProvider.ConvertingToInternal += UrlRewriteProvider_ConvertingToInternal;
}

void UrlRewriteProvider_ConvertingToInternal(object sender, EPiServer.Web.UrlRewriteEventArgs e)
{
    e.Cancel = e.Url.Path.EndsWith(".aspx");
}