Net 呼叫 Graph API 的小栗子

霖雨發表於2024-11-23

  前言

  最近,有小夥伴在做Net開發,碰到了呼叫Graph Net API的情況,在認證的時候碰到了問題,幫忙解決問題之餘,也分享給大家,希望能對遇到一樣問題的朋友有所幫助。

  正文

  程式碼比較簡單了,就是用過一個Azure App去做認證,引數就是三個,返回的GraphServiceClient物件就可以直接使用了

public GraphServiceClient CreateGraphServiceClient(string tenantId, string clientId, string clientSecret)
{
    try
    {
        var scopes = new[] { "https://graph.microsoft.com/.default" };
        var options = new TokenCredentialOptions
        {
            AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
        };

        var clientSecretCredential = new ClientSecretCredential(
            tenantId, clientId, clientSecret, options);

        GraphClient = new GraphServiceClient(clientSecretCredential, scopes);
        return GraphClient;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message.ToString());
        Console.WriteLine(ex.StackTrace);
        return null;
    }
}

  呼叫就更簡單了,先新建一個GraphServiceClient物件,然後物件會帶著你做接下來的事情了

// Create GraphServiceClient Object
GraphServiceClient graphClient = CreateGraphServiceClient("tenantId", "clientId", "clientSecret")
// Code snippets are only available for the latest version. Current version is 5.x // Dependencies using Microsoft.Graph.Models; var requestBody = new User { BusinessPhones = new List<string> { "+1 425 555 0109", }, OfficeLocation = "Huaguo Mountain, Water Curtain Cave", }; // To initialize your graphClient, see https://learn.microsoft.com/en-us/graph/sdks/create-client?from=snippets&tabs=csharp var result = await graphClient.Users["{user-id}"].PatchAsync(requestBody);

  結束語

  程式碼就是這樣,寫過一遍就會覺得非常簡單,其實也灰常簡單。

  程式碼片段來自官網,可能會跟隨Graph API的版本變化而改變(其實蠻坑的),具體程式碼可以參考官網 Update user - Microsoft Graph v1.0 | Microsoft Learn

相關文章