Redirect relative to the SharePoint LAYOUTS directory

If you ever need to redirect to a page that resides in the /_layouts/ virtual directory, i.e. the physical directory found in the SharePoint root in {SharePoint Root}\TEMPLATE\LAYOUTS it is possible to do so without hard coding the URL. Use the SPUtility.Redirect method. The signature of this method is

public static bool Redirect(string url, SPRedirectFlags flags, HttpContext context)

As you can see, this method has a parameter, flags, which should be a valid combination of the SPRedirectFlags enumeration. One of these is SPRedirectFlags.RelativeToLayoutsPage. When this is specified, along with a relative url passed as the url parameter, the redirect is performed relative to the /_layouts virtual directory.

The following example redirects to the standard SharePoint access denied page, which is referred to by a constant string made available from the SPUtility class. In this example there is no hard coding of strings at all!

SPUtility.Redirect(SPUtility.AccessDeniedPage, SPRedirectFlags.RelativeToLayoutsPage, Context);

Note this is a technique I use in my solutions to custom application pages. Create a static class called, for example, Pages and then declare string constants that enable me to get the page without having to continuously hard code it.

Why? Good question. Mainly to avoid typos – I can be 100% confident that when I call a string constant I will get the right string. If I am constantly hard coding these links then the potential for error is there. Best practice and all that…


MSDN – SPUtility.Redirect Method (String, SPRedirectFlags, HttpContext)

MSDN – SPRedirectFlags Enumeration

This entry was posted in SharePoint, SharePoint 2007, SharePoint 2010, Tips and Tricks. Bookmark the permalink.

Comments are closed.