【问题标题】:Send SMS Nexmo from Azure Function got error从 Azure Function 发送 SMS Nexmo 出错
【发布时间】:2019-12-06 12:11:02
【问题描述】:
I try to send the SMS from Azure Function, it show the error. But if i do in Web or console app the sms succesfully sent. The error is this:

System.TypeInitializationException:''Nexmo.Api.Configuration' 的类型初始化器抛出异常。'

MissingMethodException: 找不到方法:'Microsoft.Extensions.Configuration.IConfigurationBuilder Microsoft.Extensions.Configuration.MemoryConfigurationBuilderExtensions.AddInMemoryCollection(Microsoft.Extensions.Configuration.IConfigurationBuilder, System.Collections.Generic.IEnumerable1<System.Collections.Generic.KeyValuePair2>)'。

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var client = new Nexmo.Api.Client(creds: new Credentials(Api_KEY, Api_Secret));
                var results = client.SMS.Send(request: new SMS.SMSRequest()
                {
                    from = nexmo.Sender,
                    text = nexmo.Msg,
                    to = nexmo.Receiver
                });

【问题讨论】:

  • 尝试清理并重建项目。是基于V1还是V2

标签: c# azure-functions nexmo


【解决方案1】:

我意识到这是一个老问题,但我注意到它仍然没有被接受。

我刚刚使用下面的代码将最新版本的 .Net SDK (5.9.0) 与 Functions v1、v3 和 v4 一起使用,没有任何问题

using Vonage;
using Vonage.Request;
using Vonage.Messaging;

var credentials = Credentials.FromApiKeyAndSecret("abcd123efg", "abcdefgfgfgfgf");

 var VonageClient = new VonageClient(credentials);
 var response = VonageClient.SmsClient.SendAnSms(new SendSmsRequest()
 {
     To = "0123456789",
     From = "Vonage APIs",
     Text = "A text message sent using the Vonage SMS API"
  });

【讨论】:

    【解决方案2】:

    我还能够按照库克先生的方法运行新的 WhatsApp API。

    public bool Send(Message msg)
        {
            var task = SendAsync(msg);
            task.Wait();
            return task.Result;
        }
    
        public async Task<bool> SendAsync(Message msg)
        {
            var requestJson = CreateJson(msg);
            Console.WriteLine(requestJson);
            var content = new StringContent(requestJson);
            content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
            var client = new HttpClient();            
    
            try
            {
                HttpResponseMessage response = await client.PostAsync("https://messages-sandbox.nexmo.com/v0.1/messages", content);
                string responseJson = await response.Content.ReadAsStringAsync();
                return MessageSucceeded(responseJson);
            }
            catch
            {
                return false;
            }
        }
    
        private string CreateJson(Message msg)
        {
            JObject request = new JObject();
                JObject from = new JObject();
                    from.Add("type", "whatsapp");
                    from.Add("number", "14157386170");
                request.Add("from", from);
    
    
                JObject to = new JObject();
                    to.Add("type", "whatsapp");
                    to.Add("number", ConnectionData);
                request.Add("to", to);
    
                JObject message = new JObject();
                    JObject content = new JObject();
                        content.Add("type", "text");
                        content.Add("text", msg.Text);
                    message.Add("content", content);
                request.Add("message", message);
            return request.ToString();
        }
    
        private bool MessageSucceeded(string json)
        {
            var obj = JObject.Parse(json);
            JToken token;
            return obj.TryGetValue("message_uuid", out token);
        }
    

    沙盒测试的 RequestJson 是:

    { 
        "from": { "type": "whatsapp", "number": "14157386170" }, 
        "to": { "type": "whatsapp", "number": "YOUR_WHITELIST_NUMBER" }, 
        "message": { 
            "content": { "type": "text", "text": "Test succeeded. Congrats" }
        }
    }
    

    如果请求成功,ResponseJson 将包含一个 message_uuid。我只检查是否包含它

    {"message_uuid": "e6859d67-1a94-44c4-bf09-a3e3fa7f8691"}
    

    【讨论】:

      【解决方案3】:

      我遇到了同样的问题,似乎 Nexmo.Csharp.Client 包在 Azure Functions 上无法正常工作。这可能是因为其中一个程序集与 Azure 不兼容(并非全部兼容)或某些配置设置在 Azure Functions 上不受支持。

      我对安装了多少参考/程序集感到惊讶:

      安装包 Nexmo.Csharp.Client

      所以我放弃了尝试找出原因。相反,一个更简单的解决方案是创建自己的 HttpClient 并直接使用 REST API(这可能是重量级包所做的)。

              var client = new HttpClient();
      
              var requestContent = new FormUrlEncodedContent(new[] {
                  new KeyValuePair<string, string>("api_key", "YOURKEY"),
                  new KeyValuePair<string, string>("api_secret", "YOURSECRET"),
                  new KeyValuePair<string, string>("to", "TO!!!"),
                  new KeyValuePair<string, string>("from", "MisterCook"),
                  new KeyValuePair<string, string>("text", "MisterCook Says Hi")
      
              });
      
              HttpResponseMessage response = await client.PostAsync(
                  "https://rest.nexmo.com/sms/json",
                  requestContent);
      
              HttpContent responseContent = response.Content;
      
              using (var reader = new StreamReader(await responseContent.ReadAsStreamAsync()))
              {
                  // If you need it... 
              }
      

      这将使您免于部署庞大的 Nexmo.Csharp.Client 包部署并在 Azure Functions 中工作。

      【讨论】:

        【解决方案4】:

        如果它在本地或在其他环境中工作,那么代码是正确的。特别是对于 Azure Functions,我会检查依赖项是否按预期安装,并且 API 密钥等变量是否具有您预期的值(添加一些日志记录来测试这一点)——这些在无服务器上下文中的工作方式不同。希望对您有所帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-21
          • 1970-01-01
          相关资源
          最近更新 更多