【问题标题】:Calling Twilio API from C#/.NET through a Proxy Server通过代理服务器从 C#/.NET 调用 Twilio API
【发布时间】:2016-12-03 11:32:52
【问题描述】:

我正在尝试从代理 Web 服务器后面运行 C#sample twilio application。我的代理服务器需要身份验证。使用下面的代码,我能够成功地向代理服务器进行身份验证并进行 Twilio 调用。但是,Twilio 给我返回了 code 20003(权限被拒绝)。我的 AccountSID 和 AuthToken 是正确的。下面的代码(没有代理设置)在不需要网络代理服务器的不同环境中工作得很好。

我的问题类似于问题和解决方案posted here,使用 Java,但我无法使用 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();
            }
        }
    }
}

感谢您的帮助。

【问题讨论】:

    标签: c# .net proxy twilio


    【解决方案1】:

    我能够使用直接 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();
            }
        }
    }
    

    【讨论】:

    • 如果我能多点赞,我会的。似乎我的代理服务器正在删除我的 auth 标头,将其设置在 Credentials 属性上解决了我的问题!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    相关资源
    最近更新 更多