如何使用MS graph API C#搜索与搜索字符串匹配的所有文档

问题描述 投票:0回答:1

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

// ms图的应用秘密和ID天蓝色

       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
1个回答
0
投票

您可以使用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;
        });

参考

© www.soinside.com 2019 - 2024. All rights reserved.