使用 SDK 查詢 Microsoft Graph
Microsoft Graph SDK 的設計目的是簡化建置可存取 Microsoft Graph 的高品質、有效率且可復原的應用程式。 SDK 包含兩個元件:服務程式庫和核心程式庫。
服務程式庫包含從 Microsoft Graph 中繼資料產生的模型和要求建立器,以提供豐富且可探索的體驗。
核心程式庫提供一組功能,可增強使用所有 Microsoft Graph 服務。 重試處理、安全重新導向、透明驗證和承載壓縮的內嵌支援,可提升應用程式與 Microsoft Graph 互動的品質,非但不會增加複雜性,同時讓您完全掌控。 核心程式庫也支援一般工作,例如對集合進行分頁和建立批次要求。
在本單元中,您將了解可用的 SDK,並查看一些最常見作業的程式碼範例。
安裝 Microsoft Graph .NET SDK
Microsoft Graph .NET SDK 包含在下列 NuGet 套件中:
- Microsoft.Graph - 包含使用 Fluent API 存取
v1.0
端點的模型和要求建立器。Microsoft.Graph
具有Microsoft.Graph.Core
的相依性。 - Microsoft.Graph.Beta - 包含使用 Fluent API 存取
beta
端點的模型和要求建立器。Microsoft.Graph.Beta
具有Microsoft.Graph.Core
的相依性。 - Microsoft.Graph.Core - 用於呼叫 Microsoft Graph 的核心程式庫。
建立 Microsoft Graph 用戶端
Microsoft Graph 用戶端的設計目的是讓您更容易呼叫 Microsoft Graph。 您可以在應用程式的存留期內使用單一用戶端執行個體。 以下範例程式碼示範了如何建立 Microsoft Graph 用戶端執行個體。 驗證提供者會負責取得應用程式的存取權杖。 不同的應用程式提供者支援不同的用戶端案例。 如需深入了解您的案例適用的提供者和選項,請參閱選擇驗證提供者。
var scopes = new[] { "User.Read" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";
// Value from app registration
var clientId = "YOUR_CLIENT_ID";
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// Callback function that receives the user prompt
// Prompt contains the generated device code that you must
// enter during the auth process in the browser
Func<DeviceCodeInfo, CancellationToken, Task> callback = (code, cancellation) => {
Console.WriteLine(code.Message);
return Task.FromResult(0);
};
// /dotnet/api/azure.identity.devicecodecredential
var deviceCodeCredential = new DeviceCodeCredential(
callback, tenantId, clientId, options);
var graphClient = new GraphServiceClient(deviceCodeCredential, scopes);
從 Microsoft Graph 讀取資訊
若要從 Microsoft Graph 讀取資訊,您必須先建立要求物件,然後在要求上執行 GET
方法。
// GET https://graph.microsoft.com/v1.0/me
var user = await graphClient.Me
.GetAsync();
擷取實體清單
擷取實體清單與擷取單一實體類似,但有其他的要求設定選項。 $filter
查詢參數可用來將結果集縮減為僅符合所提供條件的資料列。 $orderBy
查詢參數會要求伺服器提供依指定屬性排序的實體清單。
// GET https://graph.microsoft.com/v1.0/me/messages?$select=subject,sender&$filter=<some condition>&orderBy=receivedDateTime
var messages = await graphClient.Me.Messages
.Request()
.Select(m => new {
m.Subject,
m.Sender
})
.Filter("<filter condition>")
.OrderBy("receivedDateTime")
.GetAsync();
刪除實體
刪除要求的建構方式與擷取實體要求相同,但使用 DELETE
要求取代 GET
。
// DELETE https://graph.microsoft.com/v1.0/me/messages/{message-id}
string messageId = "AQMkAGUy...";
var message = await graphClient.Me.Messages[messageId]
.Request()
.DeleteAsync();
建立新實體
對於支援 Fluent 樣式的 SDK,可以使用 Add
方法將新項目加入集合。 對於範本型 SDK,要求物件會公開 post
方法。
// POST https://graph.microsoft.com/v1.0/me/calendars
var calendar = new Calendar
{
Name = "Volunteer"
};
var newCalendar = await graphClient.Me.Calendars
.Request()
.AddAsync(calendar);