简体   繁体   中英

Sending SMS text message using twilio not working

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

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. Eg

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. Eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM