通过代理服务器从C#/.NET调用Twilio API
作者:互联网
我正在尝试从代理Web服务器后面运行C#sample twilio application.我的代理服务器需要身份验证.使用下面的代码,我能够成功地验证到代理服务器并进行Twilio调用.但是,Twilio给我返回了code 20003(权限被拒绝).我的AccountSID和AuthToken是正确的.下面的代码(不使用代理设置)在不需要Web代理服务器的其他环境中也可以正常工作.
我的问题类似于使用Java的问题和解决方案posted here,但是我无法使用C#/.NET复制Java修复程序.我正在使用.NET SDK 4.5
using System;
using Twilio;
using System.Net;
namespace TestTwilio
{
class Program
{
static void Main(string[] args)
{
var accountSid = "xx";
var authToken = "yy";
var twilio = new TwilioRestClient(accountSid, authToken);twilio.Proxy = new System.Net.WebProxy("proxy.mycompany.com", 8080);
twilio.Proxy.Credentials = new NetworkCredential(“username”, “password”);
var message = twilio.SendMessage("+1xxxxxxxxxx","+1xxxxxxxxxx", "Hello from C#");
if (message.RestException != null)
{
var error = message.RestException.Message;
Console.WriteLine(error);
Console.WriteLine(message.RestException.MoreInfo);
Console.WriteLine(message.Uri);
Console.WriteLine(message.AccountSid);
Console.Write("Press any key to continue.");
Console.ReadKey();
}
}
}
}
感谢您的帮助.
解决方法:
我能够使用直接API调用来绕过该问题.这不是解决原始问题的绝妙方法…因此仍在寻找正确的方法来解决此问题.以下是有效的代码.
using System;
using System.Net;
using RestSharp;
namespace TestTwilio
{
class Program
{
static void Main(string[] args)
{
var client = new RestClient("https://api.twilio.com/2010-04-01/Accounts/{yourTwilioAccountSID}/SMS/Messages.json");
client.Proxy = new System.Net.WebProxy("proxy.mycompany.com", 8080);
client.Proxy.Credentials = new NetworkCredential("<<proxyServerUserName>>", "<<proxyServerPassword>>", "<<proxyServerDomain>>");
var request = new RestRequest(Method.POST);
request.Credentials = new NetworkCredential("<<your Twilio AccountSID>>", "<<your Twilio AuthToken>>");
request.AddParameter("From", "+1xxxxxxxxxx");
request.AddParameter("To", "+1xxxxxxxxxx");
request.AddParameter("Body", "Testing from C# after authenticating with a Proxy");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Console.ReadKey();
}
}
}
标签:proxy,twilio,c,net 来源: https://codeday.me/bug/20191112/2023869.html