猿问

从所有 Outlook 联系人文件夹中获取联系人 Microsoft Graph

我正在使用 Microsoft Graph 使用以下代码检索联系人文件夹:


GraphServiceClient client = new GraphServiceClient(new DelegateAuthenticationProvider(

    (requestMessage) => {

        requestMessage.Headers.Authorization = 

          new AuthenticationHeaderValue("Bearer", accessToken);

        return Task.FromResult(0);

    }));


var contactsData = await client

    .Me

    .Contacts

    .Request()

    .Top(1000)

    .GetAsync();

上面的代码返回联系人,但只返回默认文件夹中的联系人。我想从用户的所有文件夹中检索联系人。


我试过先获取文件夹,然后获取他们的联系人,但它返回 a Null Reference Exceptionas Contacts are null。


var Folders = client

    .Me

    .ContactFolders

    .Request()

    .Top(1000)

    .GetAsync();


Folders.Wait();

var contacts = Folders.Result.SelectMany(a => a.Contacts).ToList();


largeQ
浏览 226回答 2
2回答

拉莫斯之舞

首先,此示例代码是在 .net core 中创建的,您应该通过以下代码在配置中设置 GraphScopes:"GraphScopes": "User.Read User.ReadBasic.All Mail.Send MailBoxSettings.ReadWrite Contacts.ReadWrite"另请注意,如果有多个文件夹,ContactFolders 只会返回结果。永远不会返回默认的联系人文件夹。如果用户没有其他文件夹,这将返回空结果。如果要获取主文件夹和需要分别获取的附加文件夹,则合并结果。// Get the defaultContactsvar defaultContacts = await graphClient&nbsp; &nbsp; .Me&nbsp; &nbsp; .Contacts&nbsp; &nbsp; .Request()&nbsp; &nbsp; .GetAsync();// Get the contactFoldersvar contactFolders = await graphClient&nbsp; &nbsp; .Me&nbsp; &nbsp; .ContactFolders&nbsp; &nbsp; .Request()&nbsp; &nbsp; .GetAsync();// Use this to store the contact from all contact folder.List<Contact> contactFolderContacts = new List<Contact>();if (contactFolders.Count > 0) {&nbsp; &nbsp; for (int i = 0; i < contactFolders.Count; i++) {&nbsp; &nbsp; &nbsp; &nbsp; var folderContacts = await graphClient&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Me&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ContactFolders[contactFolders[i].Id]&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Contacts&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Request()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .GetAsync();&nbsp; &nbsp; &nbsp; &nbsp; contactFolderContacts.AddRange(folderContacts.AsEnumerable());&nbsp; &nbsp; }&nbsp; &nbsp; // This will combine the contact from main folder and the additional folders.&nbsp; &nbsp; contactFolderContacts.AddRange(defaultContacts.AsEnumerable());} else {&nbsp; &nbsp; // This user only has the default contacts folder&nbsp; &nbsp; contactFolderContacts.AddRange(defaultContacts.AsEnumerable());}// Use this to test the result.foreach (var item in contactFolderContacts) {&nbsp; &nbsp; Debug.WriteLine("first:" + item.EmailAddresses);}

牛魔王的故事

我现在在这台机器上没有环境来测试,但据我所知,您可以使用选项查询参数来过滤子文件夹中的联系人。你需要找出所有的子文件夹获取 /users/{id |&nbsp;userPrincipalName}/contactFolders收集所有子文件夹 ID在每个子文件夹中查找联系人获取 /me/contactFolder/{id}/childFolders/{id}/contacts有关更多联系人文件夹和联系人相关信息。请阅读这些文档。&nbsp;https://developer.microsoft.com/en-us/graph/docs/api-reference/beta/api/user_list_contactfolders&nbsp;https://developer.microsoft.com/en-us/graph/docs/api-reference/beta /api/user_list_contacts
随时随地看视频慕课网APP
我要回答