【问题标题】:Upload file to Microsoft OneDrive using graph SDK using asp.net core使用 ASP.NET Core 使用图形 SDK 将文件上传到 Microsoft OneDrive
【发布时间】:2021-04-16 23:45:41
【问题描述】:

我正在尝试使用 Graph SDK for .Net Core 从工作人员服务将文件上传到 OneDrive。 基本上,有些文件是随机创建的,这些文件需要每天午夜从工作人员服务上传到 OneDrive 上的指定路径。 我在应用程序的 appconfig.json 文件中存储了以下信息:

  • 客户 ID
  • ClientSecret
  • 租户 ID

我已经检查了各个站点上的示例,但找不到使用上述IDSecret 上传文件的方法。我相信一定有某种authProvider,我可以使用上面的IDSecret 进行初始化。

我还查看了 miscrosoft 的文档,但找不到任何关于如何使用带有 IDSecret 的 SDK 上传文件的示例。

https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_put_content?view=odsp-graph-online

加分项

  • 上传新文件
  • 如果文件已经存在则覆盖(希望图表已经支持)
  • 文件大小
  • 路径格式/folder1/folder2/filename.pdf

任何帮助将不胜感激。

【问题讨论】:

    标签: asp.net-core .net-core azure-active-directory microsoft-graph-api onedrive


    【解决方案1】:

    请记住将应用程序权限(客户端凭据流)分配给应用程序注册。见Application permission to Microsoft Graph

    您可以使用Client credentials provider

    IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
        .Create(clientId)
        .WithTenantId(tenantID)
        .WithClientSecret(clientSecret)
        .Build();
    
    ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
    

    Upload small file (

    GraphServiceClient graphClient = new GraphServiceClient(authProvider);
    
    using var stream = new System.IO.MemoryStream(Encoding.UTF8.GetBytes("The contents of the file goes here."));
    
    await graphClient.Users[{upn or userID}].Drive.Items["{item-id}"].Content
        .Request()
        .PutAsync<DriveItem>(stream);
    

    如果要上传大文件,请查看Upload large files with an upload session

    更新:

    工具 -> NuGet 包管理器 -> 包管理器控制台中使用Install-Package Microsoft.Graph.Auth -IncludePrerelease

    它同时支持uploading a new filereplacing an existing item

    获取物品id的方法请参考Get a file or folder

    例如获取/folder1/folder2的item id(在Microsoft Graph Explorer进行快速测试):

    GET https://graph.microsoft.com/v1.0/users/{userID}/drive/root:/folder1:/children

    它将列出文件夹 1 中的所有子项,包括文件夹 2。然后就可以找到folder2的item id了。

    更新 2:

    客户端凭据提供者是应用程序身份,而以下所有提供者都是用户身份。

    由于您要访问个人 OneDrive(包括用户身份),您可以选择Authorization code providerInteractive provider

    授权码提供者:您需要为您的网络应用实现交互式登录并使用此提供者。

    交互式提供程序:您可以轻松地使用此提供程序在控制台应用中实现交互式登录。

    您可以通过第二家提供商进行快速测试。

    请注意,您应该将委派(个人 Microsoft 帐户)权限添加到应用注册中。见Delegated permission to Microsoft Graph

    在这种情况下,您应该将代码中的所有graphClient.Users[{upn or userID}] 修改为graphClient.Me

    恐怕您必须实现登录交互身份验证流程才能访问个人 OneDrive。

    【讨论】:

    • 感谢您的回答,能否请您告诉我需要使用哪些 nuget 包?
    • @JustAProgrammer 安装Microsoft Graph .NET SDK
    • 无法找到 Microsoft.Graph.Auth NuGet 包
    • Microsoft.Graph.Auth 仍未准备好生产,有什么替代方案?
    • 我也没有item-id,我只有/folder1/folder2/file.pdf这样的路径
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    相关资源
    最近更新 更多