在向Azure AD中托管的已注册图形API进行身份验证后,我在访问SharePoint站点文档库甚至用户OneDrive时遇到问题.好像有什么东西不见了?我使用的是最新版本的微软图形(5.6).

此代码可以工作:

using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Me.SendMail;
using Microsoft.Graph.Drives.Item.List.Items.Item.DriveItem;

namespace GraphApp
{
    class GraphHelper
    {
        //Settings object
        private static Settings? _settings;
        // User auth token credential
        private static DeviceCodeCredential? _deviceCodeCredential;
        // Client configured with user auth
        private static GraphServiceClient? _userClient;

        public static void InitializeGraphForUserAuth(Settings settings, Func<DeviceCodeInfo, CancellationToken, Task> deviceCodePrompt)
        {
            _settings = settings;

            var options = new DeviceCodeCredentialOptions
            {
                ClientId = settings.ClientId,
                TenantId = settings.TenantId,
                DeviceCodeCallback = deviceCodePrompt,
            };

            _deviceCodeCredential = new DeviceCodeCredential(options);
            _userClient = new GraphServiceClient(_deviceCodeCredential, settings.GraphUserScopes);
        }
        
        public static async Task<string> GetUserTokenAsync()
        {
            //Ensure cred isn't null
            _ = _deviceCodeCredential ??
                throw new System.NullReferenceException("Graph has not been initialized for auth");

            //Ensure scopes aren't null
            _ = _settings?.GraphUserScopes ?? throw new System.NullReferenceException("Arugment 'scopes' cannot be null");

            // Request token with given scopes
            var context = new TokenRequestContext(_settings.GraphUserScopes);
            var response = await _deviceCodeCredential.GetTokenAsync(context);
            return response.Token;
        }

        public static Task<User?> GetUserAsync()
        {
            //Ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialzed for user auth");

            return _userClient.Me.GetAsync((config) =>
            {
                //Only request specific properties
                config.QueryParameters.Select = new[] { "displayName", "mail", "userPrincipalName" };
            });
        }

MS文档指出,我应该有一个.Me.Drive.Root,但绝对没有显示在这里:我用于获取SharePoint在线驱动器的代码.

enter image description here

不确定我做错了什么,我找不到任何文档

我已经try 了所有方法,除了将HTTP GET请求发送到GRAPH之外,如果可能的话,我想避免这样做

图形帮助器的完整代码:

using Azure.Core;
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Me.SendMail;
using Microsoft.Graph.Drives.Item.List.Items.Item.DriveItem;

namespace GraphApp
{
    class GraphHelper
    {
        //Settings object
        private static Settings? _settings;
        // User auth token credential
        private static DeviceCodeCredential? _deviceCodeCredential;
        // Client configured with user auth
        private static GraphServiceClient? _userClient;

        public static void InitializeGraphForUserAuth(Settings settings, Func<DeviceCodeInfo, CancellationToken, Task> deviceCodePrompt)
        {
            _settings = settings;

            var options = new DeviceCodeCredentialOptions
            {
                ClientId = settings.ClientId,
                TenantId = settings.TenantId,
                DeviceCodeCallback = deviceCodePrompt,
            };

            _deviceCodeCredential = new DeviceCodeCredential(options);
            _userClient = new GraphServiceClient(_deviceCodeCredential, settings.GraphUserScopes);
        }
        
        public static async Task<string> GetUserTokenAsync()
        {
            //Ensure cred isn't null
            _ = _deviceCodeCredential ??
                throw new System.NullReferenceException("Graph has not been initialized for auth");

            //Ensure scopes aren't null
            _ = _settings?.GraphUserScopes ?? throw new System.NullReferenceException("Arugment 'scopes' cannot be null");

            // Request token with given scopes
            var context = new TokenRequestContext(_settings.GraphUserScopes);
            var response = await _deviceCodeCredential.GetTokenAsync(context);
            return response.Token;
        }

        public static Task<User?> GetUserAsync()
        {
            //Ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialzed for user auth");

            return _userClient.Me.GetAsync((config) =>
            {
                //Only request specific properties
                config.QueryParameters.Select = new[] { "displayName", "mail", "userPrincipalName" };
            });
        }

        public static Task<MessageCollectionResponse?> GetInboxAsync()
        {
            //Ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialized for user auth");

            return _userClient.Me
                //Only messages from Inbox
                .MailFolders["Inbox"]
                .Messages
                .GetAsync((config) =>
                {
                    //Only request specific properties
                    config.QueryParameters.Select = new[] { "from", "isRead", "receivedDateTime", "subject" };
                    // Get only top 25 results
                    config.QueryParameters.Top = 25;
                    //Sort by received time, newest first
                    config.QueryParameters.Orderby = new[] { "receivedDateTime DESC" };
                });
            
        }

        public static async Task SendMailAsync(string subject, string body, string recipient)
        {
            //ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialized for user auth");

            //Create the message
            var message = new Message
            {
                Subject = subject,
                Body = new ItemBody
                {
                    Content = body,
                    ContentType = BodyType.Text
                },
                ToRecipients = new List<Recipient>
                {
                    new Recipient
                    {
                        EmailAddress = new EmailAddress
                        {
                            Address = recipient
                        }
                    }
                }
            };

            //Send the message

            await _userClient.Me
                .SendMail
                .PostAsync(new SendMailPostRequestBody
                {
                    Message = message
                });
        }

        public static async Task GetSiteDetails(string sitename) //doesn't work
        {
            
            //ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialized for user auth");
            
            var result = await _userClient.Sites.GetAsync((requestConfiguration) =>
            {
                requestConfiguration.QueryParameters.Search = $"{sitename}";
            });
        }

        public static async Task GetDrive()
        {
            //ensure client isn't null
            _ = _userClient ??
                throw new System.NullReferenceException("Graph has not been initialized for user auth");

            var childItems = _userClient.Me.Drive.
        }

    }
}

推荐答案

首先你需要拿到你的drive id美元

var drive = await _userClient.Me.Drive.GetAsync(x=>
{
    x.QueryParameters.Select = new string[] { "id" };
});

然后用drive id来获得root件物品

var rootItem = await _userClient.Drives[drive.Id].Root.GetAsync(x =>
{
    x.QueryParameters.Select = new string[] { "id" };
});

然后使用drive idroot id来获取root中的项目

var response = await _userClient.Drives[drive.Id].Items[rootItem.Id].Children.GetAsync();
var items = response.Value.ToList();

对于SharePoint站点来说,情况非常类似

获取站点驱动器

var siteDrive = await _userClient.Sites[siteId].Drive.GetAsync();

获取站点驱动器 root item

var siteDriveRootItem = await _userClient.Drives[siteDrive.Id].Root.GetAsync();

获取项目

var response = await _userClient.Drives[siteDrive.Id].Items[siteDriveRootItem.Id].Children.GetAsync();
var items = response.Value.ToList();

Csharp相关问答推荐

在Linq中调用需要limit和offset的方法''''

数组被内部函数租用时,如何将数组返回给ArrayPool?

Blazor. NET 8—阶段启动配置文件不启动网站VS2022

dotnet集合中内部数组的局部变量副本的用途是什么?'

在具有不同属性名称的两个类之间创建关系

如何注册类使用多级继承与接口

C#DateTime.ParseExact不使用特定日期

BlockingCollection T引发意外InvalidOperationException

确定System.Text.Json序列化中是否无法识别Type

HelperText属性不支持复杂内容(混合C#和标记)

如何使用用于VS代码的.NET Maui扩展在我的iOS/Android设备或模拟器上进行调试?

无法使用[FromForm]发送带有图像和JSON的多部分请求

如何避免在.NET中将日志(log)写入相对路径

使用动态键从请求体反序列化JSON

Blazor服务器项目中的Blazor/.NET 8/Web API不工作

VS代码扩展无法在新版本扩展C#中运行从v2.10.28开始

在平行内使用跨度.用于循环

如果所有";async任务方法()";调用都返回Task.FromResult()-是否同步执行?

如何保存具有多个重叠图片框的图片框?

ASP.NET核心中的验证错误-该字段为必填字段