Pregunta

I need to get a list of subsites from a site collection.

I can navigate to the site and click on subsites and it displays all the subsites, but when I try using this code

public WebCollection GetSubSites()
{
    using (var clientContext = new ClientContext(baseUrl))
    {
        clientContext.Credentials = credentials;
        var web = clientContext.Web;
        clientContext.Load(web, website => website.Webs);
        clientContext.ExecuteQuery();
        foreach (var site in web.Webs)
        {
            var newPath = site.ServerRelativeUrl;
        }
        return web.Webs;
    }
}

I get

"Access denied. You do not have permission to perform this action or access this resource."

when calling ExecuteQuery()

Even though I'm using the same account.

How is this possible?

¿Fue útil?

Solución

The subsites that are displayed on the UI are permission trimmed.

So, there could be subsites to which you might not have access. The website.Webs will only work if you are site collection admin or owner. Else it won't work and throws the access denied error that you are having.

So, you can use the GetSubwebsForCurrentUser method to get the permission trimmed subsites.

Modify your code as below:

using (var clientContext = new ClientContext(baseUrl))
{
    clientContext.Credentials = credentials;
    var web = clientContext.Web;

    var subWebs = clientContext.Web.GetSubwebsForCurrentUser(null);

    clientContext.Load(subWebs);
    clientContext.ExecuteQuery();   

    foreach (var site in subWebs)
    {
        var newPath = site.ServerRelativeUrl;
    }
    return subWebs;
}

Reference - Web.GetSubwebsForCurrentUser method

Licenciado bajo: CC-BY-SA con atribución
scroll top