Archive

Archive for September, 2009

Be very, very careful when you use SPSite.OpenWeb()!

September 27, 2009 6 comments

I recently came across what can only be described as a shocking and dangerous bug in the SharePoint API.

According to the MSDN documentation the SPSite.OpenWeb() method:

“Returns the site that is associated with the URL that is used in an SPSite constructor.”

Below is an example of how it is very commonly used:

using (SPSite site = new SPSite("http://www.myserver.com/parentSite/childSite"))
{
using (SPWeb web = site.OpenWeb())
{
//Do your stuff
}
}

Going by the MSDN documentation the code above should return the web site located at http://www.myserver.com/parentSite/childSite. This is further confirmed by the following statement:

“When used in conjunction with an SPSite constructor, the OpenWeb method returns the lowest-level site specified by the URL that is passed as parameter for the constructor.”

This is all true if the site located at the specified url exists. But what if it doesnt exist?

Consider a scenario where an SPWeb with the url http://www.myserver.com/parentSite exists but an SPWeb with the url http://www.myserver.com/parentSite/childSite does not exist. In this scenario you would expect the code above to throw an exception, however, it does no such thing instead it ends up opening a completely different SPWeb. In this specific scenario it returns an SPWeb with the url http://www.myserver.com/parentSite. If an SPWeb didnt exist at this url as well then it would have returned the RootWeb! (i.e. http://www.myserver.com if it existed)

In other words you would end up opening and performing actions on a totally different SPWeb! As you can imagine this can have very dangerous consequences as I only very recently found!