如何使用MS graph API C#搜索所有匹配搜索字符串的文档 [英] How to use MS graph API C# to search all the documents matching search string

查看:54
本文介绍了如何使用MS graph API C#搜索所有匹配搜索字符串的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码调用来搜索 sharepoint 中的文档:

I am using below code call to search document in sharepoint :

//ms图的app secret和id azure

//app secret and id azure for ms graph

       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 搜索中有效,但在这种情况下无效.

I am using above code to search document in SharePoint. But getting unauthorized access. Same app id and secret works in MS graph Active Directory search but not in this case.

推荐答案

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

You can use the Microsoft Search API to search files stored in SharePoint or OneDrive, it supports Keyword Query Language (KQL for short) syntax in search terms of queries, for example:

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# 版本的相同示例:

Here is the same example converted to C# version:

注意:

因为 Microsoft Search API beta 版本下可用目前,您需要自己构建一个请求,如果您使用 Graph 客户端库.

since Microsoft Search API is only available under beta version at the moment, you would need to construct a request by yourself if you use 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;
        });

参考资料

这篇关于如何使用MS graph API C#搜索所有匹配搜索字符串的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆