SharePoint: Stopping redirect to access denied page

If a web is accessed that the current user doesn’t have permissions to, SharePoint’s default behaviour is to redirect you to the “access denied” page. This is true if you are trying to access it through the object model as well, even if you try to catch the System.UnauthorizedAccessException.
The workaround to this is to set the property CatchAccessDeniedException on the SPSite object to false. Once this is done, you can simply catch the unauthorised exception in your code. I.e.
using (SPSite siteCollection = new SPSite(“http://localhost/sites/blah”))
{
    siteCollection.CatchAccessDeniedException = false;
    try
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            // Attempt something here       
        }       
    }
    catch (System.UnauthorizedAccessException)
    {
        // Handle error
    }
}
Ryan Rogers has posted a good article on this at here on this (although it refers to the old version of SharePoint, it still works on MOSS / WSS 3.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>