首页 > 解决方案 > 如何使用 Microsoft Graph API (C#) 以编程方式配置个人网站 (OneDrive)

问题描述

当我尝试检索新创建的用户驱动器时,我收到一个

“未找到用户的 mysite。” 错误(代码:ResourceNotFound)

用户是在我们的本地 AD 上创建的,然后在 Azure 中同步。我已经构建了一个控制台应用程序C#,可以以编程方式分配用户许可证(基于我们的 SharePoint On-Premise 自制 IAM 解决方案),但我还需要为这些用户预先配置 OneDrive 个人网站。

我们知道如何通过 Powershell 脚本执行此操作,但我们需要使用 MS Graph API

await graphServiceClient.Users[USER_EMAIL].Drive.Request().GetAsync();

此代码引发以下错误:

“未找到用户的 mysite。”
代码:ResourceNotFound

标签: microsoft-graph-api

解决方案


我在不使用 Powershell 的情况下在 C# 中工作。下面是一个演示方法的虚拟方法。预配了 1 个用户的个人站点(用户需要拥有使用 OneDrive 的许可证)。该方法仅显示了完成此操作需要采取的步骤。在具有大量 emailId 的实时场景中,实施和重试将不起作用。创建个人网站最多可能需要 24 小时。

实现主要基于我在这里找到的内容:https ://blogs.msdn.microsoft.com/frank_marasco/2014/03/25/so-you-want-to-programmatically-provision-personal-sites-one-drive -for-business-in-office-365/

所需的 NuGet 包:

Microsoft.SharePointOnline.CSOM

波莉

虚拟方法:

private Polly.Retry.AsyncRetryPolicy WithRetry = Policy.Handle<ServiceException>().WaitAndRetryAsync(5, retryAttempt => TimeSpan.FromSeconds(Math.Pow(retryAttempt, 2)));
public async Task InitializeOneDriveForUser()
{
    var tenantAdminUrl = "https://<yourdomain>-admin.sharepoint.com";  //Replace <yourdomain> with your domain.
    var adminUserName = "youradminaccount@yourdomain";
    var adminPassword = "youradminpassword";

    var emailAddress = "youruser@yourusersdomain";
    var emailIds = new string[] { emailAddress };
    
    // Create personal site using CSOM. Maximum of 200 emailIds at a time. Might take up to 24 hours before all personal sites are created.
    using (var context = new Microsoft.SharePoint.Client.ClientContext(tenantAdminUrl))
    {
        var secureString = new System.Security.SecureString();
        foreach (char c in adminPassword)
        {
            secureString.AppendChar(c);
        }
        context.Credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(adminUserName, secureString);
        context.ExecuteQuery();

        var profileLoader = Microsoft.SharePoint.Client.UserProfiles.ProfileLoader.GetProfileLoader(context);
        profileLoader.CreatePersonalSiteEnqueueBulk(emailIds);
        profileLoader.Context.ExecuteQuery();
    }

    // Confirm that the personal site exists with a call to root. If this throws an exception, retry. The user's one drive is provisioned by a succesfull call.
    var drive = await WithRetry.ExecuteAsync(() => this.graphClient.Drives[emailAddress].Root.Request().GetAsync());

    // Get the user's OneDrive to double-check that everything is correctly provisioned and the "User's mysite not found." error is not thrown anymore.
    var usersOneDrive = await this.graphClient.Users[emailAddress].Drive.Request().GetAsync();
}

此时,为 1 个用户创建个人站点不到一分钟。如果这需要更长的时间,您将在 5 次重试后得到下​​面的 ServiceException。要解决此问题,请增加重试次数。

代码:invalidRequest 消息:提供的驱动器 ID 似乎格式错误,或不代表有效驱动器。

内在错误


推荐阅读