使用 Azure Function 设置日历事件

问题描述 投票:0回答:1

需要使用 Visual Studio 2022 和 c# 创建在日历中创建事件的 Azure 函数。

按照本指南配置 Azure 的工作负载身份联合。创建一个服务帐户并将其连接到该功能。创建了 Azure 函数,用于通过 Google Cloud 进行身份验证,然后创建日历事件。使用常规 VS 应用程序通过服务帐户尝试了此方法,并且它有效,因此日历的所有权限都应该没问题。使用 Azure Function 时,没有任何反应,但部署和发布正常。添加了一些日志,也许可以了解问题出在哪里,但在 Azure 门户上看不到任何日志(不知道为什么)。

这是代码:-

using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;

namespace setEvent
{
    public class babam
    {
        private readonly ILogger _logger;

        public babam(ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<babam>();
        }

        [Function("babam")]
        public HttpResponseData Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestData req)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");
            try
            {
                _logger.LogInformation("Получение учетных данных сервисного аккаунта.");
                // Инициализируем учетные данные сервисного аккаунта.
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                .CreateScoped(CalendarService.Scope.Calendar);

                // Создаем сервис для доступа к API Календаря.
                _logger.LogInformation("Создание сервиса для доступа к API Календаря.");
                var service = new CalendarService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Calendar API .NET Quickstart"
                });
                string calendarId = "36e41687bff738ba3c57426d98d17a37e604fa99485a38d1c18cc2f1e8225114@group.calendar.google.com";
                var newEvent = new Event
                {
                    Summary = "New event",
                    Location = "Haifa",
                    Start = new EventDateTime()
                    {
                        DateTime = DateTime.Parse("2024-04-30T09:00:00+02:00"),
                        TimeZone = "Asia/Jerusalem",
                    },
                    End = new EventDateTime()
                    {
                        DateTime = DateTime.Parse("2024-04-30T10:00:00+02:00"),
                        TimeZone = "Asia/Jerusalem",
                    },
                };

                // Выполняем запрос к API Календаря.
                var createdEvent = service.Events.Insert(newEvent, calendarId).Execute();
                _logger.LogInformation("Событие успешно создан.");
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Произошла ошибка при создании события.");
            }
            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "text/plain; charset=utf-8");

            response.WriteString("Welcome to Azure Functions!!!");

            return response;
        }
    }
}

c# azure azure-functions
1个回答
0
投票

在您的代码中,您没有提供正确的凭据。

这段代码对我有用

作为参考,请检查此文档

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using Google.Apis.Auth;
using Google.Apis.Calendar.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;


namespace calenderevent
{
    public class Function1
    {
        private readonly ILogger<Function1> _logger;

        public Function1(ILogger<Function1> logger)
        {
            _logger = logger;
        }

        [Function("Function1")]
        public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");

             string[] scopes = { CalendarService.Scope.Calendar };
             string AppName = "calenderdotnet";


            UserCredential credential;

            using (var stream =
                new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                string credstorePath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credstorePath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credstorePath);
            }

            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = AppName,
            });

            // create events.
            var newEvent = new Event
            {
                Summary = "New event",
                Location = "Haifa",
                Start = new EventDateTime()
                {
                    DateTime = DateTime.Parse("2024-04-30T09:00:00+02:00"),
                    TimeZone = "Asia/Jerusalem",
                },
                End = new EventDateTime()
                {
                    DateTime = DateTime.Parse("2024-04-30T10:00:00+02:00"),
                    TimeZone = "Asia/Jerusalem",
                },
            };

            var createevent = service.Events.Insert(newEvent, "primary").Execute();
            _logger.LogInformation($"calender event created{createevent.HtmlLink}");


            return new OkObjectResult("Welcome to Azure Functions!");
        }
    }
}

注意:

CalenderId
永远是
primary

OUTPUT

© www.soinside.com 2019 - 2024. All rights reserved.