Dealing with anonymous access to a website, I found some rather interesting behavior where a Redirect handler I had written was throwing a NullReferenceException.  It turns out that the SPContext.Web property includes some fairly complex logic that under certain circumstances creates a new SPWeb instance. As a result, it may fail with the NullReferenceException, although that behavior is not documented (Big surprise for the MSCryptic fans…)

In my case it dealt with an application page in the _layouts folder that was set for anonymous access using the UnsecuredLayoutsPageBase class.  My RunWithElevatedPrivileges code block was creating problems when trying to access certain properties using the SPContext.Current.Site object.

The solution was to instantiate a local variable outside the using block to hold the user’s current site and then read properties from the local variable once inside the RunWithElevatedPrivileges block in order to avoid the NullReferenceException.  Here is the code:

protected override void OnPreInit(EventArgs e)
{
    // site and web objects working with the current user's privileges
    SPSite userSite = SPContext.Current.Site;
    
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
        // get new site and web objects working with elevated privileges
        using (SPSite thisSite = new SPSite(userSite.ID))
        {
            //Code here using thisSite instead of SPContext.Current.Site....
        }
    } 
}