Sending SMS text message using twilio not working

浪尽此生 提交于 2020-01-05 10:25:14

问题


I am trying to send SMS message from c# unit test code but I am not able to receive the text message and I don't know where to debug this.

Also, inside my response object, I get the value "Bad Request". What am I doing wrong. Also in while loop, I wait for the response to get processed.

Here is my code.

   [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;
    }

回答1:


You're making an asynchronous request, but not waiting for the result. Try:

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

Also, you should be able to format your parameters more easily/safely using the FormUrlEncodedContent type, instead of StringContent. It appears to be made to support what you're trying to do. E.g.

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

And since this creates a different request body than your content, this might be the cause of your "Bad Request" error. The two ways of doing this encode special characters, both the &'s separating the portions and the strings themselves, quite differently. E.g.

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


来源:https://stackoverflow.com/questions/18950415/sending-sms-text-message-using-twilio-not-working

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!