Google 日历 Api v3 asp.net 代码 200,但未插入事件

Google Calendar Api v3 asp.net Code 200, yet no event inserted

你好,

我目前正在 asp.net 核心中构建约会查找器。我在访问日历时设法获得了代码 200。

但是,Google 日历没有保存我要发送的事件。控制台仪表板显示已收到。帐户中只有一个日历。

到目前为止我的代码:

 public void InsertIntoCalendar()
    {
        var Cal = new CalendarEvents();
        var newEvent = Cal.CreateEvent("TestEvent", "RandomLocation", "Description", "2017-07-28");
        var service = CreateService();

        service.Events.Insert(newEvent, serviceAccountEmail).Execute();

            String calendarId = "primary";
            EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
            Event createdEvent = request.Execute();
    }

CalendarEvents 是一个 class,它通过多种方法创建事件。 我尝试使用事件 class 本身,但结果是一样的。

服务是这样创建的:

        private CalendarService CreateService()
    {
        string keyFilePath = "random.p12;

        var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);

        ServiceAccountCredential credential = new ServiceAccountCredential(
            new ServiceAccountCredential.Initializer(serviceAccountEmail)
            {
                Scopes = Scopes
            }.FromCertificate(certificate));

        // Create the service.
        CalendarService service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            //ApplicationName = "ShowCase",
        });

        return service;
    }

在 cshtml 页面上,我使用 razor 执行此操作:

            CalendarConnection TestConnection = new CalendarConnection();
            TestConnection.InsertIntoCalendar();     

我收到代码 200,但事件未插入到日历中。我读了关于这个的 perl 文章,但我无法从中得到任何东西。

我做错了什么?

提前谢谢你。

编辑: 当我从控制台应用程序调用 events.list 时,我可以看到事件:

测试(2017 年 7 月 26 日 20:58:08)

测试(2017 年 7 月 26 日 20:58:57)

测试(2017 年 7 月 26 日 21:03:38)

测试(2017 年 7 月 26 日 21:05:27)

为什么我在日历中看不到它们?

我发现了错误。

实际上问题不是我的代码。

首先,如果您使用 "primary" 作为日历 ID,它就不是我帐户的日历 ID。您可以从中获取事件,但它不会显示在您的日历中。一位同事建议它是一种沙盒日历(或错误)。

在我从帐户输入日历 ID 后(您的主要电子邮件地址或您在日历设置中找到的地址),我收到错误 403。

这是由于没有与服务帐户地址共享日历(由Google创建服务帐户时创建的地址,通常如XXXXX@xxxxx.iam.gserviceaccount.com)

所以,如果您想通过 Google 日历创建活动:

  1. https://console.developers.google.com

  2. 创建一个服务帐户
  3. 与服务帐户的电子邮件地址共享您的日历。

  4. 使用上面的代码(或使用 client_secrets.json 的代码)

注意:并不总是您的代码,而是缺少一些管理工作。

代码在这里:

 public void InsertIntoCalendar()
{
    var Cal = new CalendarEvents();
    var newEvent = Cal.CreateEvent("TestEvent", "RandomLocation", "Description", "2017-07-28");
    var service = CreateService();

    service.Events.Insert(newEvent, serviceAccountEmail).Execute();

        String calendarId = "XXXXXX@group.calendar.google.com"; // or the e-mail address of the Google account if you want to use the primary calendar
        EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
        Event createdEvent = request.Execute();
}