问题描述
我正在尝试从 c# 单元测试代码发送 SMS 消息,但我无法接收文本消息,而且我不知道在哪里调试.
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.
此外,在我的响应对象中,我得到值错误请求".我究竟做错了什么.同样在 while 循环中,我等待响应得到处理.
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.
这是我的代码.
[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;
此外,您应该能够使用 FormUrlEncodedContent
类型,而不是 StringContent
.它似乎是为了支持您正在尝试做的事情.例如
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);
由于这会创建与您的 content
不同的请求正文,因此这可能是导致错误请求"错误的原因.两种对特殊字符进行编码的方法,即 &
分隔部分和字符串本身,完全不同.例如
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&To=+5678901234&Body=hi & bye+2
这篇关于使用 twilio 发送 SMS 文本消息不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!