【问题标题】:Google API Service Account InitialisationGoogle API 服务帐号初始化
【发布时间】:2015-06-29 15:00:45
【问题描述】:

我正在开发一项服务,该服务应该能够使用服务帐户将日历事件插入到来自各个 Google Apps 域的用户日历中。一切正常,但是我在使用 Google API 初始化服务时遇到了一个小问题。 Google API 中描述的初始化如下所示:

        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 是否已连接。然而,提供的代码 sn-p 不运行任何底层网络通信 - 它只是初始化服务。整个身份验证过程在执行事件时发生,例如: var eventResult = newEventRequest.Execute();

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

提前谢谢你。

【问题讨论】:

    标签: .net google-api google-calendar-api google-apps


    【解决方案1】:

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

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

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

    【讨论】:

    • 没有必要存储实际令牌,因为它已经存储在凭证实例中,并且将被传递到 CalendarService 本身不是吗?因此我尝试了这个:try { var auth = credential.RequestAccessTokenAsync(CancellationToken.None).Result; } catch (Exception ex) { Console.WriteLine(ex.ToString()); return null; } 工作正常,但是所有异常都嵌套在 AggregateException 中:/
    • 可能会帮助有同样问题的人。 stackoverflow.com/questions/21483599/….
    猜你喜欢
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 2018-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多