GraphServiceClient returns empty list when searching for SharePoint sites with an empty string as search term

Towards the end of last year, I supported a teammate with troubleshooting. It was about searching pages in SharePoint via Microsoft Graph API using GraphServiceClient. The following code returned an empty list.

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Graph;

using SharepointList = Microsoft.Graph.List;

namespace Backend.Infrastructure.Microsoft.Graph.Sharepoint
{
    internal class SiteLogic
    {
        private readonly GraphServiceClient graphClient;

        public SiteLogic(GraphServiceClient graphClient)
        {
            this.graphClient = graphClient;
        }

        public async Task<List<Site>> GetSitesAsync()
        {
            var queryOptions = new List<QueryOption>()
            {
                new QueryOption("search", ""),
            };

            var sites = await graphClient.Sites.Request(queryOptions).GetAsync();
            var allSites = new List<Site>(sites);

            while (sites.NextPageRequest != null)
            {
                sites = await sites.NextPageRequest.GetAsync();
                allSites.AddRange(sites);
            }

            return allSites;
        }

        public async Task<SharepointList> SearchListByName(string siteId, string listName)
        {
            var lists = await graphClient.Sites[siteId].Lists.Request().GetAsync();
            var foundList = lists.FirstOrDefault(list => list.Name == listName);

            while (foundList == null && lists.NextPageRequest != null)
            {
                lists = await lists.NextPageRequest.GetAsync();
                foundList = lists.FirstOrDefault(list => list.Name == listName);
            }

            return foundList;
        }
    }
}

According to the documentation and as tested in the Graph Explorer, all sites should be returned…

After some debugging which included enabling logging of requests in the Microsoft Graph .NET client library, we figured out that GraphServiceClient (Microsoft.Graph version 4.48.0) ignores QueryOptions with empty string as value. Consequently, we were able to solve the problem as follows:

var queryOptions = new List<QueryOption>()
{
        new QueryOption("search", "*"),
};

Important: make sure the user/application has the required permissions!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Website Powered by WordPress.com.

Up ↑

%d bloggers like this: