【问题标题】:How to use MS graph API C# to search all the documents matching search string如何使用 MS graph API C# 搜索匹配搜索字符串的所有文档
【发布时间】:2020-03-11 14:28:31
【问题描述】:

我正在使用下面的代码调用来搜索共享点中的文档:

//ms graph 的app secret 和id azure

       string cSecret = "XXXX";
       string cId = "XXXXXXXX";

        var scopes = new string[] { "https://graph.microsoft.com/.default" };
        var confidentialClient = ConfidentialClientApplicationBuilder
      .Create(cId)
      .WithAuthority($"https://login.microsoftonline.com/murphyoil.onmicrosoft.com/v2.0")
      .WithClientSecret(cSecret)
      .Build();

        string requestUrl;
        GraphServiceClient graphClient =
        new GraphServiceClient(new DelegateAuthenticationProvider(async (requestMessage) =>
        {
            var authResult = await confidentialClient
    .AcquireTokenForClient(scopes)
    .ExecuteAsync();

            // Add the access token in the Authorization header of the API request.
            requestMessage.Headers.Authorization =
            new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authResult.AccessToken);
        }));


        requestUrl = "https://graph.microsoft.com/beta/search/query";

        var searchRequest = new
        {
            requests = new[]
                    {
            new
            {
                entityTypes = new[] {"microsoft.graph.driveItem"},
                query = new
                {
                    query_string = new
                    {
                        query = "policy AND filetype:docx"
                    }
                },
                from = 0,
                size = 25
            }
        }
        };
        //construct a request
        var message = new HttpRequestMessage(HttpMethod.Post, requestUrl);
        var jsonPayload = graphClient.HttpProvider.Serializer.SerializeObject(searchRequest);
        message.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
        await graphClient.AuthenticationProvider.AuthenticateRequestAsync(message);
        var response = await graphClient.HttpProvider.SendAsync(message);
        //process response 
        var content = await response.Content.ReadAsStringAsync();
        var result = JObject.Parse(content);
        var searchItems = result["value"].First["hitsContainers"].First["hits"].Select(item =>
        {
            var itemUrl = (string)item["_source"]["webUrl"];
            return itemUrl;
        });
    }

我正在使用上面的代码在 SharePoint 中搜索文档。 但获得未经授权的访问。相同的应用程序 ID 和密码在 MS 图形 Active Directory 搜索中有效,但在这种情况下不可用。

【问题讨论】:

  • 这个问题有什么解决办法吗?

标签: c# sharepoint microsoft-graph-api


【解决方案1】:

您可以使用Microsoft Search API 来搜索存储在SharePoint 或OneDrive 中的文件,它支持Keyword Query Language (KQL for short) 语法在查询的搜索词中,例如:

POST /search/query
Content-Type: application/json
{
  "requests": [
    {
      "entityTypes": [
        "microsoft.graph.externalFile"
      ],
      "query": {
        "query_string": {
          "query": "contoso AND filetype:docx"
        }
      },
      "from": 0,
      "size": 25
    }
  ]
}

这是转换为 C# 版本的相同示例:

注意

因为 Microsoft Search API beta 版本下可用 目前,您需要自己构建一个请求,如果 你使用Graph Client Library

仅支持以下权限

Delegated (work or school account)    Mail.Read, Files.Read.All, Calendars.Read, ExternalItem.Read.All
var graphClient = AuthManager.GetClient("https://graph.microsoft.com/");


var requestUrl = "https://graph.microsoft.com/beta/search/query";
var searchRequest = new
        {
            requests = new[]
            {
                new
                {
                    entityTypes = new[] {"microsoft.graph.driveItem"},
                    query = new
                    {
                        query_string = new
                        {
                            query = "contoso AND filetype:docx"
                        }
                    },
                    from = 0,
                    size = 25
                }
            }
};
//construct a request
var message = new HttpRequestMessage(HttpMethod.Post, requestUrl);
var jsonPayload = graphClient.HttpProvider.Serializer.SerializeObject(searchRequest);
message.Content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(message);
var response = await graphClient.HttpProvider.SendAsync(message);
//process response 
var content = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(content);
var searchItems = result["value"].First["hitsContainers"].First["hits"].Select(item =>
        {
            var itemUrl = (string) item["_source"]["webUrl"];
            return itemUrl;
        });

参考文献

【讨论】:

  • 我正在使用有问题的更新后的 graphClient,但我遇到了未经授权的异常。
  • @AllTech,您需要指定 Files.Read.All 权限,因为您的目标是 SharePoint 或 OneDrive
  • var scopes = new string[] { "graph.microsoft.com/Files.Read.All" };我使用了上面的几行但得到了错误::提供的请求必须包含一个“范围”输入参数。为输入参数“范围”提供的值无效。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多