Google API 服务帐户初始化

Google API Service Account Initialisation

我正在开发一项服务,该服务应该能够使用服务帐户将日历事件插入来自各种 Google 应用程序域的用户日历中。一切正常,但是我在使用 Google API 初始化服务时遇到了一个小问题。 Google APIs 中描述的初始化看起来像这样:

        string[] scopes = new string[] { CalendarService.Scope.Calendar };
        var certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
        try
        { 
            ServiceAccountCredential credential = new ServiceAccountCredential(
                new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL) 
                {
                    User = user,
                    Scopes = scopes
                }.FromCertificate(certificate));

            CalendarService service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
            });
            return service;
        }

        catch (Exception ex)
        {
            return null;
        }

我遇到的问题是,我希望能够在实际尝试插入任何事件之前检查 CalendarService 是否已连接。但是,提供的代码片段不会 运行 任何底层网络通信 - 它只是初始化服务。整个身份验证过程在执行事件时发生,例如: var eventResult = newEventRequest.Execute();

有什么好的方法可以在创建任何事件(检查 HttpRequestException、TokenResponseException 等)之前检查服务是否实际连接?我能想到的唯一解决方案是插入一个简单的事件,然后在之后立即删除它,或者根本不使用 Google API。

提前致谢。

尝试像这样预先刷新令牌:

if(credential.RequestAccessTokenAsync(CancellationToken.None).Result)
{
    AuthenticationKey = credential.Token.AccessToken;
}

这将尝试刷新访问令牌,本质上是为您提供检查服务连接的方法。