当我的响应数据是通过 webhook 获取时,如何从 Azure Function 同步响应?

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

我有一个 HTTP 触发的 Azure 函数(函数 A),用于响应 Webhook。

我现在遇到的问题是,现在在我的 Azure 函数中,我需要调用 API 来获取响应数据,但这个新 API 只接收我的请求并向我发送 ACK 响应,以及来自该 API 的真实响应通过 webhook 发送。

我可以创建另一个 HTTP 触发的 Azure 函数(函数 B)来接收来自新 API 的数据,但如何将此数据传递给我原来的 Azure 函数(函数 A)以同步响应。

任何帮助将不胜感激。

azure-functions webhooks
1个回答
0
投票

HTTP 触发器同步处理请求。在返回之前,应该有一个结果要返回。

您可以执行以下操作:

  1. 接收入站请求。
  2. 调用 API。
  3. 检查循环中结果是否准备好。
  4. 然后:
    1. 如果结果已就绪,则返回。
    2. 如果花费太多时间,则请求失败。

下面的示例代码。备注:

  • 尚未做好生产准备
  • 您应该通过 DI 正确注入
    HttpClient
  • 您应该实施正确的错误处理
  • 您应该实施正确的请求/响应处理
[Function("Function1")] public async Task<IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequest req) { // Configure a hard timeout of 5 seconds var ct = new CancellationTokenSource(TimeSpan.FromSeconds(5)).Token; HttpClient _client = new() { BaseAddress = new Uri("https://example.com") }; // Make the initial request to get `ACK` var creationResponse = await _client.PostAsync("/", new StringContent("CREATE")); // While not timeout while (!ct.IsCancellationRequested) { // Sleep for 1 second await Task.Delay(TimeSpan.FromSeconds(1)); // Exit if timed out if (ct.IsCancellationRequested) break; // Make a check request var response = await _client.GetAsync("/"); // If it is successful, if (response.IsSuccessStatusCode) { // Read the content var content = await response.Content.ReadAsStringAsync(); // Respond return new OkObjectResult(content); } } // Otherwise (when cancellation token triggered by a timeout), throw an exception throw new TimeoutException("TIMEOUT"); }
    
© www.soinside.com 2019 - 2024. All rights reserved.