Skip to main content
 首页 » 编程设计

c#之使用 twilio 发送 SMS 短信不起作用

2024年02月13日16birdshome

我正在尝试从 c# 单元测试代码发送 SMS 消息,但我无法接收文本消息,而且我不知道在哪里调试它。

此外,在我的响应对象中,我得到值“Bad Request”。我究竟做错了什么。 同样在 while 循环中,我等待响应得到处理。

这是我的代码。

   [TestMethod] 
    public void TestMethod1() 
    { 
        Assert.IsTrue(SendMessage("+1MYFROMPHONENUMBER", "+1MYTOPHONENUMBER", "sending from code")); 
    } 
 
    public bool SendMessage(string from, string to, string message) 
    { 
        var accountSid = "MYACCOUNTSIDFROMTWILIOACCOUNT"; 
        var authToken = "MYAUTHTOKENFROMTWILIOACCOUNT"; 
        var targeturi = "https://api.twilio.com/2010-04-01/Accounts/{0}/SMS/Messages"; 
        var client = new System.Net.Http.HttpClient(); 
        client.DefaultRequestHeaders.Authorization = CreateAuthenticationHeader("Basic", accountSid, authToken); 
        var content = new StringContent(string.Format("From={0}&To={1}&Body={2}", from, to, message)); 
        content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); 
        var result = false; 
        var response = client.PostAsync(string.Format(targeturi, accountSid), content).Result; 
        do 
        { 
            result = response.IsSuccessStatusCode; 
        } while (result == false); 
        return result; 
    } 

请您参考如下方法:

您正在发出异步请求,但不等待结果。尝试:

var response = client.PostAsync(..).Result; 
return response.IsSuccessStatusCode; 

此外,您应该能够使用 FormUrlEncodedContent 类型而不是 StringContent 更轻松/安全地格式化您的参数。它似乎是为了支持你正在尝试做的事情。例如

var dict = new Dictionary<string, string> 
    { { "From", from }, { "To", to }, { "Body", message } }; 
var content = new FormUrlEncodedContent(dict); 

由于这会创建与您的内容 不同的请求主体,因此这可能是您的“错误请求”错误的原因。执行此操作的两种编码特殊字符的方式非常不同,& 分隔部分和字符串本身。例如

string from = "+1234567890", to = "+5678901234", message = "hi & bye+2"; 
//FormUrlEncodedContent results: 
From=%2B1234567890&To=%2B5678901234&Body=hi+%26+bye%2B2 
//StringContent results: 
From=+1234567890&amp;To=+5678901234&amp;Body=hi & bye+2