C# – Microsoft Graph – 无法访问OneDrive/SharePoint站点的文档库

huangapple go评论78阅读模式
英文:

C# - Microsoft Graph - Can't access OneDrive/SharePoint site document library

问题

I'll provide a translation of the relevant code snippet you've provided:

我在通过在Azure AD中托管的注册图形API进行身份验证后,访问SharePoint站点的文档库或用户的OneDrive时遇到了问题。似乎有些东西丢失了?我正在使用最新版本的Microsoft Graph5.6)。

此代码有效:

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

namespace GraphApp
{
    class GraphHelper
    {
        // 设置对象
        private static Settings? _settings;
        // 用户身份验证令牌凭据
        private static DeviceCodeCredential? _deviceCodeCredential;
        // 配置用户身份验证的客户端
        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()
        {
            // 确保凭据不为空
            _ = _deviceCodeCredential ??
                throw new System.NullReferenceException("未对身份验证初始化Graph");

            // 确保作用域不为空
            _ = _settings?.GraphUserScopes ?? throw new System.NullReferenceException("参数'scopes'不能为空");

            // 使用给定的作用域请求令牌
            var context = new TokenRequestContext(_settings.GraphUserScopes);
            var response = await _deviceCodeCredential.GetTokenAsync(context);
            return response.Token;
        }

        public static Task<User?> GetUserAsync()
        {
            // 确保客户端不为空
            _ = _userClient ??
                throw new System.NullReferenceException("未对用户身份验证初始化Graph");

            return _userClient.Me.GetAsync((config) =>
            {
                // 仅请求特定属性
                config.QueryParameters.Select = new[] { "displayName", "mail", "userPrincipalName" };
            });
        }
    }
}

请注意,这只是你提供的代码片段的一部分。如果需要翻译其他部分,请提供具体的代码。

英文:

I'm having issues accessing a sharepoint sites document library or even the users onedrive after authenticating to a registered graph api hosted in Azure AD. It seems like things are missing? I'm using the latest version of microsoft graph (5.6).

This code works:

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 Documentation states i should have a .Me.Drive.Root but absolutely nothing shows up here: My code for getting SharePoint Online drives.

C# – Microsoft Graph – 无法访问OneDrive/SharePoint站点的文档库

Not sure what I'm doing wrong and I can't find any documentation

I've tried everything except posting HTTP get requests to graph which I want to avoid if possible

Entire code of graph helper:

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.
}
}
}

答案1

得分: 3

首先,您需要获取您的 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();

获取站点驱动的根项目:

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();
英文:

First you need to get your drive id

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

Then use the drive id to get the root item

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

Then use the drive id and the root id to get items in the root

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

For SharePoint site it's very similar

Get site drive

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

Get site drive root item

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

Get items

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

huangapple
  • 本文由 发表于 2023年4月17日 08:47:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/76031027.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定