0

尝试创建 WebHook 订阅时,部署无法在 Azure Functions 中为 Cloud Events v1.0 架构验证 HTTP 触发器。我已确认我的端点处理了具有适当响应的验证握手。我的事件网格域正在使用 Cloud Events v1.0 架构。看来我的 Azure 函数在验证期间甚至没有被调用,因为该函数的控制台中没有输出。

这是否适用于 Cloud Events v1.0 和 WebHooks?

部署失败并出现以下错误:{"code":"Url validation","message":"验证提供的端点 xxxxx 的尝试失败。"}

这是我的代码:

[FunctionName("ProcessEvent")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequestMessage req, ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var requestmessage = await req.Content.ReadAsStringAsync();
            var message = JToken.Parse(requestmessage);

            if (message.Type == JTokenType.Array)
            {
                // If the request is for subscription validation, send back the validation code.
                if (string.Equals((string)message[0]["eventType"],
                "Microsoft.EventGrid.SubscriptionValidationEvent",
                System.StringComparison.OrdinalIgnoreCase))
                {
                    log.LogInformation("Validate request received");

                    var myObj = new { validationResponse = message[0]["data"]["validationCode"].ToString() };
                    var jsonToReturn = JsonConvert.SerializeObject(myObj);

                    return new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new StringContent(jsonToReturn, Encoding.UTF8, "application/json")
                    };
                }
            }
            else
            {
                // The request is not for subscription validation, so it's for an event.
                // CloudEvents schema delivers one event at a time.
                log.LogInformation($"Source: {message["source"]}");
                log.LogInformation($"Time: {message["eventTime"]}");
                log.LogInformation($"Event data: {message["data"].ToString()}");
            }

            return req.CreateResponse(HttpStatusCode.OK);
}
4

1 回答 1

1

CloudEvents v1.0的端点验证与此处描述的EventGridSchemaCustomInputSchema等交付模式不同。

出于测试目的,您可以使用Webhook.site作为端点处理程序。以下屏幕显示了 EventGrid 为验证握手发送OPTIONS调用:

在此处输入图像描述

请注意,端点处理程序的地址必须是https。如上图所示,有一个webhook-request-callback头。复制其值 a 并将其放在浏览器上并发送。您应该得到以下文本:

"Webhook succesfully validated as a subscription endpoint."

从现在开始,webhook 可以接收到一个 Notification 消息,看下面的屏幕:

在此处输入图像描述

如您所见,CloudEvent v1.0 需要为端点验证实现 HTTP OPTIONS 响应。以下是此实现的示例:

string webhookcallback = req.Headers.GetValues("WebHook-Request-Callback")?.FirstOrDefault()?.Trim();       
if(string.IsNullOrEmpty(webhookcallback) == false)
{
    var hrm2 = req.CreateResponse(HttpStatusCode.OK);
    hrm2.Headers.Add("WebHook-Request-Origin", "eventgrid.azure.net");
    hrm2.Headers.Add("WebHook-Allowed-Rate", "120");

    System.Threading.ThreadPool.QueueUserWorkItem(delegate (object state)
    {
        Task.Delay(5000).Wait();
        using(var client = new HttpClient())
        {
            log.Warning($"{client.GetAsync(webhookcallback).Result.Content.ReadAsStringAsync().Result}");
        }
    });

    return hrm2;
}

将上面的代码片段放入您的函数中。注意,WebHook-Request-Callback地址的调用不能在OPTIONS 调用中,必须在其 OK 响应返回 EventGrid 之后进行,因此我们有一些延迟和后台线程。如果 EventGrid 将在 OPTIONS 调用中接受此调用,那就太好了。

于 2020-01-07T15:59:16.483 回答