从 C# 服务中使用 Graph API 获取日历计划

Get calendar schedules with Graph API from C# service

我需要使用 Microsoft Graph API 通过 .NET Core Windows 服务从日历中获取 free/busy 日程安排。根据微软自己的文档,我应该使用以下内容:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var schedules = new List<String>()
{
    "adelev@contoso.onmicrosoft.com",
    "meganb@contoso.onmicrosoft.com"
};

var startTime = new DateTimeTimeZone
{
    DateTime = "2019-03-15T09:00:00",
    TimeZone = "Pacific Standard Time"
};

var endTime = new DateTimeTimeZone
{
    DateTime = "2019-03-15T18:00:00",
    TimeZone = "Pacific Standard Time"
};

var availabilityViewInterval = 60;

await graphClient.Me.Calendar
    .GetSchedule(schedules,endTime,startTime,availabilityViewInterval)
    .Request()
    .Header("Prefer","outlook.timezone=\"Pacific Standard Time\"")
    .PostAsync();

我已经使用 Azure 门户注册了一个新应用程序并授予它权限 Calendars.Read。

我的 C# 代码:

try
{
    IConfidentialClientApplication clientApplication = ConfidentialClientApplicationBuilder
        .Create(_clientId)
        .WithTenantId(_tenantId)
        .WithClientSecret(_clientSecret)
        .Build();

    var authProvider = new ClientCredentialProvider(clientApplication);
    var graphClient = new GraphServiceClient(authProvider);

    var schedules = new List<string>
    {
        "example@mail.com" // not actual mail used in my application
    };

    var startTime = new DateTimeTimeZone
    {
        DateTime = "2020-04-18T00:00:00",
        TimeZone = "Europe/Paris"
    };

    var endTime = new DateTimeTimeZone
    {
        DateTime = "2020-04-25T23:59:59",
        TimeZone = "Europe/Paris"
    };

    ICalendarGetScheduleCollectionPage scheduleList = await graphClient.Me.Calendar
        .GetSchedule(schedules, endTime, startTime, 60)
        .Request()
        .PostAsync().ConfigureAwait(false);
    Console.WriteLine("scheduleList.Count: " + scheduleList.ToList().Count);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

当我 运行 我的应用程序出现以下异常时:

代码:BadRequest

消息:当前经过身份验证的上下文对此请求无效。当向需要用户登录的端点发出请求时,会发生这种情况。例如,/me 需要登录用户。代表用户获取令牌以向这些端点发出请求。对移动和本机应用程序使用 OAuth 2.0 授权代码流,对单页 Web 应用程序使用 OAuth 2.0 隐式流。

您正在使用 Client credentials provider 创建 authProvider。

但是,客户端凭据仅适用于仅限应用的权限。

但是在您的代码中 graphClient.Me.Calendar 意味着您正在尝试获取 "my calendar",表示已登录用户的日历。

但是没有登录用户,因为客户端凭据仅限应用程序。

因此,如果您有登录用户,则需要实施 Authorization code provider。然后就可以使用graphClient.Me.Calendar获取日历了。

或者如果您没有登录用户,您应该继续使用客户端凭据提供程序并将代码修改为:graphClient.Users["objectId of the user"].Calendar.