Friday, March 25, 2011

Custom 404 Page not found error page - SharePoint

SharePoint is a content management system, so people creates thousands of pages and at the same time deletes hundreds or thousands of pages, if you hit one of page in deleted pages then you will get page not found error (blue and white screen page), but the problem is the error page is not user friendly, you will not find any redirection link, so how will you solve this problem?

Usually, we apply 404 page at IIS virtual directory level, but how will you apply same for SharePoint website?

In SharePoint when we create web application using SharePoint central administration internally that will create a virtual directory under IIS, so now our job is so easy, just check below code, the SPWebApplication refers to Virtual Directory

Create a feature receiver and add below code in to FeatureActivated method

See, the web application class contains a property called “FileNotFoundPage” just apply your custom 404 page to that property

SPSite curSiteColl = properties.Feature.Parent as SPSite;
System.Uri webApplicationUri = new Uri(curSiteColl.Url);
SPWebApplication webApplication = SPWebApplication.Lookup(webApplicationUri);
webApplication.FileNotFoundPage = "404ErrorPage.html";
webApplication.Update();

The property accepts only HTML page, so we need to assign HTML page and then using Java script redirect to our custom .aspx page

<html>
<head>
<meta HTTP-EQUIV="Content-Type" content="text/html; charset=utf-8" />
<meta HTTP-EQUIV="Expires" content="0" />
<script language="javascript" src="/_layouts/1033/init.js"></script>
<script language="javascript" src="/_layouts/1033/core.js"></script>
<script language="javascript">
var requestedUrl = escapeProperly(window.location.href);
STSNavigate("/_layouts/ErrorPages/404ErrorPage.aspx?oldUrl=" + requestedUrl);
</script>
</head>
<body>
</body>
</html>

Now, open the 404ErrorPage.aspx page and add whatever message you want under place holder main section

<asp:Content ID="mainContent" ContentPlaceHolderID="PlaceHolderMain" runat="server">
<table>
<tr>
<td class="ErrorPageTitle" >
<span class="ErrorPageTitle1">Page Not Found</span>
</td>

</tr>
<tr>
<td> <span class="ErrorPageMsg1">The page you requested could not be found. Use this link<http://mspbox.blogspot.com> to redirect to home page </td>
</tr>
</table>
</asp:Content>

0 comments:

Post a Comment