Net 调用 Graph API 的小栗子

  前言

  最近,有小伙伴在做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

posted @ 2024-11-23 00:30  霖雨  阅读(1)  评论(0编辑  收藏  举报