Getting a "Trying to use an SPWeb object that has been closed or disposed" Exception? It’s this line in your custom application.master page

Posted: Jon | Comments: 0 | March 1st, 2011
Mar 01

So there I was, minding my own and pooting forth the little green rosettas on a branding solution for a publishing site, when I navigated over to the site collection’s Keyword Management page (/_layouts/listkeywords.aspx). Only, instead of visually pleasing Keyword Management functionality besetting my oculars, I encountered the following White Screen of Death:

Microsoft.SharePoint.SPException: Trying to use an SPWeb object that has been closed or disposed and is no longer valid. at Microsoft.Office.Server.Search.Internal.UI.SearchAdminPageBase.ErrorHandler(Object sender, EventArgs e)

Of course, it’s SharePoint Development 101 to have properly disposed of any SPSite or SPWeb objects we create. At the same time, we have to be careful not to toss out the current SPContext‘s reference to these same types, at the risk of seeing just such an error as above.

Luckily, this was just a branding project, and there were precious few lines of custom server-side code that could be culprit in this case. So, my joy would lie in sifting through a few .cs files for a wayward disposal of the current web object, right?

Yes, but joy wouldn’t have warranted a blog post. That’s how I know the SharePoint API really loves me.

CustomApplication.master v. Drawing Board

After a hardy scrubbing of the Internet floor for an answer to my dilemma, I found a single reference to this exact situation. Sadly, the solution given was less than specific:

Instead of taking a copy of default.master, try taking a copy of application.master and modify that one.

So, re-build an entire master page?

The moral is that I should have done it this way from the beginning, but rework at this late hour would cause more boogers than it would un-cause. Instead, I took the tack of digging into the out-of-the-box copies of default.master and application.master, hunting for the very difference that would unleash our titular error.

Now, I could go on and on and on about the subtleties that set these two master page layouts apart, and that might be funny to someone standing over your watching you read this post, turning colors while you scan for the copy and paste bit.

But you’re here for the answer, and you’re clearly no fun at all, so, here. Take the following line out of your version of application.master, and our mystery error will take its ball and go home:

<WebPartPages:SPWebPartManager ID="m" runat="Server" />

You’ll forgive me if I leave it as an exercise to the abused reader to explain why this mysterious control would clearly violate SharePoint coding principals like, say, not disposing of the current SPWeb object.

I, for one, am going to go ahead and try to my afternoon back.

Leave a Comment