【问题标题】:How to map a list of dynamically generated properties from Twilio's WhatApp for business如何从 Twilio WhatsApp 为企业映射动态生成的属性列表
【发布时间】:2021-12-13 01:10:29
【问题描述】:

再次寻求帮助;让我解释一下:我一直致力于集成 WhatsApp for Business,以便为我们的客户提供一种向我们发送图片的方式,以便我们可以使用 Azure AI 处理它们。

到目前为止,我已经完成的是启用 Web API 服务作为 Twilio 的 webhook 的端点,并且信息流动得非常好,我遇到的唯一问题是:Twilio 将通过以下方式连接到我的 Web API网络挂钩并以application/x-www-form-urlencoded 格式执行POST,在所有Request 参数中,我需要访问作为消息一部分的文件列表(参考:https://www.twilio.com/docs/messaging/guides/webhook-request#media-related-parameters)。

文档提到,如果有超过 1 个带有消息的附加文件,它将使用从零开始的索引来命名每个文件,所以基本上它是一个动态的 url 列表,我需要映射到一个不能动态的对象。

这是WhatsAppMessage 型号:

public class WhatsAppMessage
{
    public string MessageSid { get; set; }
    public string AccountSid { get; set; }
    public string MessagingServiceSid { get; set; }
    public string From { get; set; }
    public string To { get; set; }
    public string Body { get; set; }
    public string NumMedia { get; set; }

    public List<string> MediaList { get; set; } //from Twilio as MediaUrl{n}
}

这是我用来处理这些帖子的代码:

[HttpPost("webhook")]
public IActionResult WebhookInterface([FromForm]WhatsAppMessage whatsAppMessage)
{
    StringBuilder stringBuilder = new();
    stringBuilder.Append($"Hola, dijiste '{whatsAppMessage.Body}', desde el número {whatsAppMessage.From} \n");
    int numAdjuntos = int.Parse(whatsAppMessage.NumMedia);
    stringBuilder.Append($"Hay {numAdjuntos} archivos adjuntos al mensaje. \n");

    if (numAdjuntos > 0)
    {
        // How do I access each MediaUrl{n} which are part of the Form?
        // Will be good to have a List<string> to save this urls
    }

    stringBuilder.Append($"URL de imagen: {whatsAppMessage.MediaUrl0}");

    return Ok(stringBuilder.ToString());
}

我知道这听起来并不难,但我正在为此苦苦挣扎!任何帮助都会很有价值!

【问题讨论】:

    标签: c# asp.net-web-api twilio


    【解决方案1】:

    根据文档,您的 Web API 可能需要多个 MediaUrl 和 MediaContentType 参数。一种解决方案是使用dynamic 类型,然后如果存在任何媒体,则使用循环手动迭代。

    HTTP 请求示例:

    POST / HTTP/2.0
    Host: foo.com
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 296
    
    NumMedia=2&MessageSid=SMXX&SmsSid=SMXX&MediaContentType0=image/jpeg&MediaUrl0=bla.com&MediaContentType1=image/png&MediaUrl1=starwars.com
    

    API 端点:

    [HttpPost("webhook")]
    public IActionResult WebhookInterface([FromForm] dynamic whatsAppMessage)
    {
        int numAdjuntos = whatsAppMessage.NumMedia;
    
        // 1st iteration: extract MediaUrl0 & MediaContentType0
        // 2nd iteration: extract MediaUrl1 & MediaContentType1 ...
        for (int i = 0; i < numAdjuntos; i++)
        {
            string mediaUrl = whatsAppMessage[$"MediaUrl{i}"];
            string mediaContentType = whatsAppMessage[$"MediaContentType{i}"];
            // ...
        
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-07-22
      • 2020-10-29
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2021-09-27
      • 2023-02-22
      相关资源
      最近更新 更多