Access denied with SPSite.AllWebs

When you require a collection containing all the SPWeb objects in a specific site collection, the SPSite.AllWebs property seems to be sufficient. This statement is only correct as long as the current user is a site collection administrator..

but when the code is executed in the context of a user in the Member or Visitor group, an Access Denied message appears!

If you are not sure that the functionality is exclusive for administrators, try to avoid the following code:

SPContext.Current.Web.Site.AllWebs.ToList();

Instead I recommend the following approach by using the GetSubwebsForCurrentUser :

private static IList GetAllWebsSafely(){
    var allwebs = SPContext.Current.Web.Site.RootWeb.GetSubwebsForCurrentUser().ToList();
    allwebs.Add(SPContext.Current.Site.RootWeb);
    return allwebs;
}

In my case I needed an equivalent of the AllWebs, including the rootweb object. Therefor the rootweb is also added to the collection.

Hope this helps,
Tom.

VN:F [1.9.22_1171]
Rating: 8.6/10 (7 votes cast)
VN:F [1.9.22_1171]
Rating: +1 (from 3 votes)
Access denied with SPSite.AllWebs, 8.6 out of 10 based on 7 ratings