如何使用 Microsoft Graph API 从搜索的文件中获取内容(文本)?

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

首先,我使用sdk 4.x版本。

我想使用图形API从onedrive创建搜索功能。

在Teams(应用程序)搜索功能案例中,当我使用搜索功能时,应用程序返回文件内容信息并显示压力搜索关键字。

我想显示该文件的内容(不是全文,仅包括搜索关键字)

但是,搜索响应不包含内容。

那么,如何替换这个功能呢?还是我用错了这个api?

这是我的搜索请求代码。

 var searchResults = await graphServiceClient
     .Drives[driveId2]
     .Root
     .Search(searchQuery)
     .Request()
     .GetAsync();

在图浏览器案例中(Http 请求)

https://graph.microsoft.com/v1.0/me/drives/b!SoVLl_cMV0m-LhNDYBjj_A-mBCIl-3dEoicDMVnEfVABgoGg2gexQ7frRHmqg2GK/root/search(q='')

此外,要响应的内容请求案例包括 ReadTimeout 和 WriteTimeout


var searchResults = await graphServiceClient
        .Drives[driveId]
        .Items[fileId]
        .Content
        .Request()                   
        .GetAsync();
c# asp.net-core microsoft-graph-api microsoft-graph-sdks
1个回答
0
投票

首先,我们现在有Search API来满足您的要求,您可以看一下链接,看看请求内容和响应。那么当前文档仅向我们展示了 SDK v5 的示例。如有必要,请不要忘记添加所需的权限

File.Read.All Sites.Read.All
Files.ReadWrite.All Sites.ReadWrite.All
。这是代码。

using Microsoft.Graph.Search.Query;
using Microsoft.Graph.Models;

var requestBody = new QueryPostRequestBody
{
    Requests = new List<SearchRequest>
    {
        new SearchRequest
        {
            EntityTypes = new List<EntityType?>
            {
                EntityType.ExternalItem,
            },
            ContentSources = new List<string>
            {
                "/external/connections/connectionfriendlyname",
            },
            Region = "US",
            Query = new SearchQuery
            {
                QueryString = "contoso product",
            },
            From = 0,
            Size = 25,
            Fields = new List<string>
            {
                "title",
                "description",
            },
        },
    },
};

var result = await graphClient.Search.Query.PostAsQueryPostResponseAsync(requestBody);

但是由于您尝试使用V4 sdk,但我没有找到官方示例或其他示例,我认为我们可以有一个解决方法,直接发送http请求而不是使用SDK。由于您已经在代码中使用了 GraphClient,我相信您也有类似于以下代码的代码,其中包含

EnableTokenAcquisitionToCallDownstreamApi

builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi()
    .AddInMemoryTokenCaches();

然后我们可以在Controller中注入

ITokenAcquisition
来生成访问令牌,并使用它来调用查询API。

public class HomeController : Controller
{
    private readonly ITokenAcquisition _tokenAcquisition;
    public HomeController(ITokenAcquisition tokenAcquisition)
    {
        _tokenAcquisition = tokenAcquisition;
    }
    
    public async Task IndexAsync(){
        var accessToken = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "File.Read.All", "Sites.Read.All" });
        var request ="{{\"requests\": [{{\"entityTypes\": [\"driveItem\", \"listItem\", \"list\"],\"query\": {{\"queryString\": \"contoso\"}]}}";
        var content = new StringContent(request, Encoding.UTF8, "application/json");
        var httpReqMesg = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/search/query")
        {
            Headers =
            {
                { HeaderNames.Authorization, "Bearer "+ accessToken}
            },
            Content = content
        };
        var httpClient = _httpClientFactory.CreateClient();
        var response = await httpClient.SendAsync(httpReqMesg);
        var res = "";
        if (response.StatusCode == HttpStatusCode.OK)
        {
            res = await response.Content.ReadAsStringAsync();
        }
    }

}

顺便说一句,如果您使用的是没有 ITokenAcquisition 的客户端凭据流。我们可以使用下面的代码来生成访问令牌。

var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenantId";
var clientId = "clientId";
var clientSecret = "clientSecret";
var clientSecretCredential = new ClientSecretCredential(
                tenantId, clientId, clientSecret);
var token = clientSecretCredential.GetTokenAsync(tokenRequestContext).Result.Token;
© www.soinside.com 2019 - 2024. All rights reserved.